给定一字符串,求它的组合结果

给定一个字符串,求出该字符串的所有组合(假设无重复字符)
str=“abc”,那么其组合有[a,b,c,ab,ac,bc,abc]

思路:
以abc为例,它的组合的结果为 2的3次方-1,即7种。那么枚举1——7,则每个值的二进制可代表一种情况:
1: 001 str[2] -----> c
2: 010 str[1] -----> b
3: 011 str[1]+str[2] -----> bc
4: 100 str[0] -----> a
5: 101 str[0]+str[2] -----> ac
6: 110 str[0]+str[1] -----> ab
7: 111 str[0]+str[1]+str[2] -----> abc

代码实现:

private static List<String> combine(String str){
        List<String> re=new ArrayList<>();
        int len=str.length();
        int allConditions=(int)Math.pow(2,len)-1;

        for (int i = 1; i <= allConditions; i++) {
            String binary=Integer.toBinaryString(i);
            //  上面得到的二进制不一定就是len长度的,前面的0被省略掉了
            //  因为当二进制串的位置j如果为1的话,会去str中取出对应str[j]作为结果
            //  所以这里需要记录差值
            int div=len-binary.length();

            StringBuilder temp=new StringBuilder();
            for(int j=binary.length()-1;j>-1;j--){
                if (binary.charAt(j)=='1'){
                    temp.append(str.charAt(div+j));
                }
            }
            re.add(temp.toString());
        }

        return re;
    }

补充:
去重的话,直接用set,没想到其它好的办法。

参考:
https://www.cnblogs.com/boris1221/p/9388209.html

类似问题:

leetcode:77. 组合
输入: n = 4, k = 2
输出:
[
[2,4],
[3,4],
[2,3],
[1,2],
[1,3],
[1,4],
]

基于回溯算法,注意过程中的剪枝。

	public List<List<Integer>> combine(int n, int k) {
        List<List<Integer>> re=new ArrayList<>();
        if(n<1 || k<1){
            return re;
        }
        combineConcrete(n,k,re);
        return re;
    }

    static LinkedList<Integer> stack=new LinkedList<>();

    public  void combineConcrete(int n, int k,List<List<Integer>> re) {
    	//	k==0表示得到一组解
        if (k==0){
            re.add(new ArrayList<>(stack));
            return;
        }
        //	剪枝:n<=0了,肯定没法在放了。n<k这里思路是,现在需要还需要k个数,但是剩余的能够组合的数的个数n,已经小于了k
        if (n<=0 || n<k){
            return;
        }

        //  组合包含第n个数的情况
        stack.push(n);
        //  剩余的子问题为:在剩下n-1个数中选择k-1数,组成k个数的组合
        combineConcrete(n-1,k-1,re);


        //  组合不包含第n个数的情况
        //  先把上面放进去的第n个数弹出
        stack.pop();
        //  剩余子问题为,在剩下n-1个数中选择k个数,组成k个数的组合
        combineConcrete(n-1,k,re);
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值