对给定字符串求所有的组合

该博客介绍了如何对给定字符串求所有可能的组合。通过将字符串转换为01串表示法,详细阐述了解题思路,包括如何输出每个组合,并分析了算法的空间复杂度为n,时间复杂度为2^n-1,解释了存在这么多组合的原因。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

输入字符串,输出所有的组合,比如输入abc,输出 a b c ab ac bc abc。

题目解法:abc用01串表示,001表示输出c,111表示输出abc,解法如下。。。空间复杂度n,时间复杂度为2^n-1,因为有这么多种结果啊。。。

package combination;

/**
 * 
 * @author Administrator
 * 输出所有的组合,比如输入abc,输出 a b c ab ac bc abc
 * 
 * boolean初始化默认为false,
 */
public class Combination {

	public static void combination(char[] cs) {
		int len = cs.length;
		boolean[] choosed = new boolean[len];
		char[] cache = new char[len];
		int result = len;
		int index = 0;
		while(true) {
			index = 0;
			while (choosed[index]) {
				choosed[index] = false;
				++result;
				if (++index == len) {
					return;
				}
			}
			choosed[index] = true;
			cache[--result] = cs[index];
			System.out.println(new String(cache).substring(result) + "  ");
		}
		
	}
	
	public static void main(String[] args) {
		String sourceString = "abc";
		char[] cs = sourceString.toCharArray();
		combination(cs);
		/*
	    a  
		b  
		ab  
		c  
		ac  
		bc  
		abc  
		 */
		/**
		 * 步骤:
		 * 初始:              a b c 
		 * choose: 0 0 0
		 *         1 0 0   a
		 *         0 1 0   b
		 *         1 1 0   ab
		 *         0 0 1   c
		 *         1 0 1   ac
		 *         0 1 1   bc
		 *         1 1 1   abc
		 *         
		 *         要保证在后一个字符进来不能覆盖前一个字符,但个数一样时可以,比如a b ,但有了b,a进入时要在b之前
		 *         
		 *         
		 */
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值