LeetCode第三十九题-求组合所有可能性

Combination Sum

问题简介:给定一个数组(没有重复元素)和一个目标值,找到数组中元素可以组成目标值所有组合
注:
1.数组元素可以重复使用
2.所有数字(包括目标)都是正整数
3.解决方案集不得包含重复的组合
举例:
1:
输入: candidates = [2,3,6,7], target = 7,
结果:
[
[7],
[2,2,3]
]
2:
输入: candidates = [2,3,5], target = 8,
结果:
[
[2,2,2,2],
[2,3,3],
[3,5]
]
解法一:
利用递归的思想,先将给定数组排序,这样在求和过程中,例如i处数字大于目标值,就不需要算i处往后的数值了,递归过程中将target值不断减去数组中的值,直到为0才添加到结果集合中

class Solution {
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        List<List<Integer>> res = new ArrayList<>();
        Arrays.sort(candidates);
        Recursive(res,candidates,target,new ArrayList(),0);
        return res;
    }

    public void Recursive(List<List<Integer>> res, int[] candidates, int target,
                                   List<Integer> tempList,int index) {
        if (target == 0) {
            res.add(tempList);
            return;
        }
        for (int i = index; i < candidates.length; i++) {
            if (candidates[i] <= target) {
                List<Integer> list = new ArrayList<>(tempList);
                list.add(candidates[i]);
                Recursive(res,candidates,target - candidates[i],list,i);
            } else {
                break;
            }
        }
    }
}

小白刷题之路,请多指教— — 要么大器晚成,要么石沉大海

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值