数据结构与算法之递归题目

数据结构与算法之递归题目


目录

  1. 求n!的结果
  2. 汉若塔问题
  3. 打印字符串的全部子序列,包括空字符串
  4. 打印一个字符串的全部排序

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. 打印字符串的全部子序列,包括空字符串

  1. 题目描述:打印一个字符串的全部排序,要求不要出现重复的排序

  2. 思路:遍历字符,每个字符都可能被打印,或者不被打印(" ")

  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;
	}
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值