暴力递归——打印所有的子序列

import java.util.ArrayList;
import java.util.List;

//打印一个字符串的全部子序列,包括空字符串
public class PrintAllSubsquences {

	public static void printAllSubsquence(String str) {
		char[] chs = str.toCharArray();
		process(chs, 0);
	}

	//当前来到i位置
	public static void process(char[] chs, int i) {
		//如果i已经抵达终止位置,直接打印值
		if (i == chs.length) {
			System.out.println(String.valueOf(chs));
			return;
		}
		//新增下一个字符进入考虑范围,并把之前的字符串也考虑进去
		process(chs, i + 1);
		char tmp = chs[i];
		chs[i] = 0;
		process(chs, i + 1);//不要当前字符的路
		chs[i] = tmp;
	}
	
	public static void function(String str) {
		char[] chs = str.toCharArray();
		process(chs, 0, new ArrayList<Character>());
	}

	//当前来到i位置,要和不要,走两条路
	// res 之前的选择,所形成的列表
	public static void process(char[] chs, int i, List<Character> res) {
		if(i == chs.length) {
			printList(res); // 如果 i 来到了终止位置,打印之前的选择
			return;
		}
		List<Character> resKeep = copyList(res);
		resKeep.add(chs[i]);
		process(chs, i+1, resKeep); // 要当前字符的路
		List<Character> resNoInclude = copyList(res);
		process(chs, i+1, resNoInclude); // 不要当前字符的路
	}
	
	public static void printList(List<Character> res) {
		// ...;
	}
	
	public static List<Character> copyList(List<Character> list){
		return null;
	}
	

	public static void main(String[] args) {
		String test = "abc";
		printAllSubsquence(test);
	}

}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值