组合求和 Combination Sum

组合总和问题解析

问题:

Given a set of candidate numbers (C(without duplicates) and a target number (T), find all unique combinations in C where the candidate numbers sums to T.

The same repeated number may be chosen from C unlimited number of times.

Note:

  • All numbers (including target) will be positive integers.
  • The solution set must not contain duplicate combinations.

For example, given candidate set [2, 3, 6, 7] and target 7
A solution set is: 

[
  [7],
  [2, 2, 3]
]

解决:

① 结果要求返回所有符合要求解的题十有八九都是要利用到递归,而且解题的思路都大同小异,需要另写一个递归函数。注意是可以连续选择同一个数加入组合的。与方法②一样

class Solution { //17 ms
    public static List<List<Integer>> combinationSum(int[] candidates, int target){
        Arrays.sort(candidates);
        List<List<Integer>> res = new ArrayList<>();
        List<Integer> cur = new ArrayList<>();
        dfs(candidates,0,target,cur,res);
        return res;
    }
    private static void dfs(int[] candidates, int i, int target, List<Integer> cur, List<List<Integer>> res) {//i表示当前遍历到的下标。
        if(target < 0)    return;
        if(target == 0){
           
res.add(new ArrayList<>(cur));
            return;
        }

        for(int j = i; j < candidates.length && target >= candidates[j]; j ++){
            cur.add(candidates[j]);
            dfs(candidates,j,target - candidates[j],cur,res);//递归向后查找
            cur.remove(cur.size() - 1);//还原链表
        }
    }
}

② 简化

class Solution { //19ms
    List<List<Integer>> res = new ArrayList<>();  
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        List<Integer> cur = new ArrayList<>();
        dfs(candidates, 0, target, cur);
        return res;
    } 
    private void dfs(int[] nums, int i,int target, List<Integer> cur) {//i表示当前遍历到的位置
        if (target == 0) {
            res.add(new ArrayList<>(cur));
            // return;
        }    
        for (int j = i; j < nums.length; j ++) {
            if (nums[j] <= target) {
                cur.add(nums[j]);
                dfs(nums, j, target - nums[j], cur);
                cur.remove(cur.size() - 1);
            }
        }
    } 
}

转载于:https://my.oschina.net/liyurong/blog/1528471

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值