数据结构与算法之递归题目
目录
1. 求n!的结果
public static long getFactorial1(int n) {
if (n == 1) {
return 1L;
}
return (long) n * getFactorial1(n - 1);
}
2. 汉若塔问题
// N : 1~N
public static void process(int N,String from,String to, String help){
if (N ==1){
System.out.println("Move 1 from "+from+" to "+ to);
}else {
process(N-1,from,help,to);
System.out.println("Move "+N +" from "+from+" to "+to);
process(N-1,help,to,from);
}
}
3. 打印字符串的全部子序列,包括空字符串
-
题目描述:打印一个字符串的全部排序,要求不要出现重复的排序
-
思路:遍历字符,每个字符都可能被打印,或者不被打印(" ")
-
代码实现
public class Code_Print_All_Subsquences {
public static void printAllSub(char[] str,int i, String res){
if (i == str.length){
System.out.println(res);
return;
}
printAllSub(str,i+1,res);
printAllSub(str,i+1,res+String.valueOf(str[i]));
}
public static void main(String[] args) {
String test = "abc";
printAllSub(test.toCharArray(),0,"");
}
}
4. 打印一个字符串的全部排序
代码实现
public static void process(char[] chs, int i) {
if (i == chs.length) {
System.out.println(String.valueOf(chs));
}
HashSet<Character> set = new HashSet<>();
for (int j = i; j < chs.length; j++) {
if (!set.contains(chs[j])) {
set.add(chs[j]);
swap(chs, i, j);
process(chs, i + 1);
}
}
}
public static void swap(char[] chs, int i, int j) {
char tmp = chs[i];
chs[i] = chs[j];
chs[j] = tmp;
}