本文目录一览:
java中递归算法是怎么算的?
- 汉诺塔问题
import javax.swing.JOptionPane;
public class Hanoi {
private static final String DISK_B = "diskB";
private static final String DISK_C = "diskC";
private static final String DISK_A = "diskA";
static String from = DISK_A;
static String to = DISK_C;
static String mid = DISK_B;
public static void main(String[] args) {
String input = JOptionPane.showInputDialog("please input the number of the disks you want me move.");
int num = Integer.parseInt(input);
move(num, from, mid, to);
}
private static void move(int num, String from2, String mid2, String to2) {
if (num == 1) {
System.out.println("move disk 1 from " + from2 + " to " + to2);
} else {
move(num - 1, from2, to2, mid2);
System.out.println("move disk " + num + " from " + from2 + " to " + to2);
move(num - 1, mid2, from2, to2);
}
}
}
- 排列示例
这是一个排列的例子,它所做的工作是将输入的一个字符串中的所有元素进行排序并输出。例如:参数是
"abc"
,程序会输出:
abc
acb
bac
bca
cab
cba
- 出口条件:
low == high
,即排列元素只有一个时。 - 逼近过程:先确定排列的第一位元素,然后从
low+1
开始减少排列元素,直到low == high
。
public static void permute(String str) {
char[] strArray = str.toCharArray();
permute(strArray, 0, strArray.length - 1);
}
public static void permute(char[] list, int low, int high) {
int i;
if (low == high) {
String cout = "";
for (i = 0; i <= high; i++)
cout += list[i];
System.out.println(cout);
} else {
for (i = low; i <= high; i++) {
char temp = list[low];
list[low] = list[i];
list[i] = temp;
permute(list, low + 1, high);
temp = list[low];
list[low] = list[i];
list[i] = temp;
}
}
}
- 组合示例 这是一个组合的例子,输出所给字符串中指定数目的元素的组合种类。
- 出口条件:
n == 1
,此时输出目标数组的所有元素。 - 逼近过程:当
n > 1
时,先取第一个元素放入目标数组中,然后n-1
,如此下去。
import javax.swing.JOptionPane;
public class Combination {
public static void main(String[] args) {
String input = JOptionPane.showInputDialog("please input your String: ");
String numString = JOptionPane.showInputDialog("please input the number of your Combination: ");
int num = Integer.parseInt(numString);
Combine(input, num);
}
private static void Combine(String input, int num) {
char[] a = input.toCharArray();
String b = "";
Combine(a, num, b, 0, a.length);
}
private static void Combine(char[] a, int num, String b, int low, int high) {
if (num == 0) {
System.out.println(b);
} else {
for (int i = low; i < a.length; i++) {
b += a[i];
Combine(a, num - 1, b, i + 1, a.length);
b = b.substring(0, b.length() - 1);
}
}
}
}
用java递归方法实现
- 递归定义:递归是一种算法,在程序设计语言中广泛使用,是指函数/过程/子程序在运行过程中直接或间接调用自身而产生的重入现象。
- 递归解决的问题类型:
- 数据的定义是按递归定义的(如 Fibonacci 函数)。
- 问题解法按递归算法实现(如回溯)。
- 数据的结构形式是按递归定义的(如树的遍历、图的搜索)。
JAVA中的递归方法,求讲一下。
方法递归和循环语句类似,打个比喻:方法递归是小明上楼拿东西,从一楼、二楼、三楼……直到楼顶。在楼顶拿到想要的东西后,不能直接跳下来,必须一层一层返回。循环则是驴拉磨,转多少圈都在原地,变化的只是盘子里的东西。 方法递归不会进入死循环,但如果递归太深,系统可能会崩溃。 答得不好,抱歉。
在JAVA中什么是递归?有什么用?
Java 方法递归是指在一个方法的内部调用自身的过程。其思想是将规模大的问题转化为规模小的相似子问题来解决。在函数实现时,因为解决大问题的方法和解决小问题的方法往往是同一个方法,所以会产生函数调用自身的情况。 递归的两个条件:
- 通过递归调用来缩小问题规模,且新问题与原问题具有相同的形式。
- 存在一种简单情境,使递归在简单情境下退出,避免无限递归。