Combination SumIII; BackTracking; Array;

本文详细解析了组合求和问题的递归算法实现,并通过具体示例代码展示了如何找到所有可能的有效组合。针对参数为列表的情况,特别强调了在递归过程中如何避免重复元素的问题。

Note that when you put the list to be the parameter, and each time you do the recursion, you add element into the list, you need to remove the former added elements in the previous combination.

Code:

public class Solution {
    public List<List<Integer>> combinationSum3(int k, int n) {
        List<List<Integer>> ret = new ArrayList<>();
        List<Integer> list = new ArrayList<>();
        combination(list, ret, k, n, 0, 1);
        return ret;
    }
    
    public void combination(List<Integer> list, List<List<Integer>> ret, int k, int remain, 
                int last, int index){
        if(remain < last+1) return;
        if(index == k){
            if(remain > 9) return;
            list.add(remain);
            ret.add(new ArrayList(list));
            list.remove(list.size()-1);
            return;
        }
        for(int i = last+1; i <= remain && i <= 9; i++){
                //if(!status) break;
                if(index == 1) list = new ArrayList<>();
                list.add(i);
                combination(list, ret, k, remain-i, i, index+1);
                list.remove(list.size()-1);
        }
    }
    
}

 

转载于:https://www.cnblogs.com/5683yue/p/5229563.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值