算法-重复组合

一、题目描述

  • 给定一个不重复数组char[] ch,从数组中取出num 个元素,将num个元素组合起来,求有多少种组合
  • 例如:
数组 char[] ch:{"a", "b", "c"};    
元素num :取出3个元素

结果:10种
[a, a, b]
[b, b, c]
[a, a, a]
[c, c, c]
[a, b, c]
[a, a, c]
[a, b, b]
[b, b, b]
[a, c, c]
[b, c, c]
  • 找规律的方式
思路一: (思想,使用了就不再使用)
111,112,113,114
122,123,124
133,134
144

222,223,224
233,234
244

333,334
344

444

思路二: (思想,  3个a有多少种, 2个a有多少种, 1个a有多少种组合)
aaa														1 
aab,aac,aad												3
abb,	abc,abd,	acc,acd,	add						6 
bbb,	bbc,bbd,	bcd,bcc,bdd,	ccc,ccd,cdd,ddd		10

二、解决

方案一(不推荐)

  • 循环遍历后去重
 public static void main(String[] args) {
        String[] combineSource = {"a", "b", "c"};
        HashSet<String> combineRes = new HashSet<>();
        combine(combineSource, combineRes, 3L);
        for (String com: combineRes){
            System.out.println(com);
        }
        System.out.printf(combineRes.size() + "");
    }

    public static void combine(String[] combineSource, Set<String> combineRes, Long remainTotalNum) {
        combine(combineSource, combineRes, "", remainTotalNum);
    }
    public static void combine(String[] combineSource, Set<String> combineRes, String combineStr, Long remainTotalNum) {
        String prxStr = combineStr;
        for (String str: combineSource) {
            combineStr = prxStr +  str;
            if (combineStr.length() == remainTotalNum) {
                char[] chars = combineStr.toCharArray();
                Arrays.sort(chars);
                combineRes.add(Arrays.toString(chars));
                continue;
            }
            combine(combineSource, combineRes, combineStr, remainTotalNum);
        }
    }

方案二

  • 使用了就不再使用,这个实现是元素没有重复的实现
class Solution {
    List<List<Integer>> lists =new ArrayList<>();
    List<Integer> list=new ArrayList<>();
    int num=0;
    public List<List<Integer>> combine(int n, int k) {
        int[] a=new int[n];
        num=k;
        for(int i=0;i<n;i++){
            a[i]=i+1;
        }
        dfs(a,0);
        return lists;
    }
    public void dfs(int[] a,int i){
        if(list.size() == num){
            lists.add(new ArrayList<>(list));
            return;
        }
        if(i == a.length){
            return;
        }
        list.add(a[i]);
        dfs(a,i+1);	
        //dfs(a,i);//请注意,如果要求组合方式中有可以重复的元素,此处不加1
        list.remove(list.size()-1);
        dfs(a,i+1);
    }

    /**
     * 从 n个元素中获取k个元素; 其中n表示 1到n 的数字: 例如n=10 则表示1到10的数字
     * @param args
     */
    public static void main(String[] args) {
        Solution solution = new Solution();
        List<List<Integer>> combine = solution.combine(2, 2);
        System.out.printf("");
    }
}

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值