【剑指offer】之字符串的组合



 题目:

     输入一个字符串,输出该字符串中字符的所有组合。举个例子,如果输入abc,它的组合有abcabacbcabc


分析:

    假设我们想在长度为n的字符串中求m个字符的组合。我们先从头扫描字符串的第一个字符。针对第一个字符,我们有两种选择:一是把这个字符放到组合中去,接下来我们需要在剩下的n-1个字符中选取m-1个字符;而是不把这个字符放到组合中去,接下来我们需要在剩下的n-1个字符中选择m个字符。这两种选择都很容易用递归实现。


java代码实现:

  

	private static void combination(String str) {
		char[] chars = getChars(str);
		
		Stack stack = new Stack();
		for(int i=1;i<=chars.length;i++) {
			combination(chars,0, i,stack);
		}
	}
	
	private static void combination(char[]chars, int index, int number,Stack stack) {
		
		if(number == 0) {
			Iterator iterator = stack.iterator();
			while(iterator.hasNext()) {
				System.out.print(iterator.next());
			}
			System.out.print(" ");
			return ; //如果不返回,则会出现重复的字符组合
		}
		
		if(index == chars.length)
			return ;
		
		stack.push(chars[index]);
		combination(chars, index+1,number-1,stack);
		stack.pop();
		
		combination(chars, index+1,number,stack);
		
	}
	
	private static char[] getChars(String str) {
		char[] temp = new char[str.length()];
		for(int i=0;i<str.length();i++) {
			temp[i] = str.charAt(i);
		}
		return temp;
	}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值