39. Combination Sum

39. Combination Sum

Tag BackTracing

Difficulty Medium

Link https://leetcode-cn.com/problems/combination-sum/

思路

这道题与77题n选k类似,只不过多了一个可以重复取数的条件,依然使用深度优先搜索遍历,画图可以使得我们看得更加直观。

假设candidates=[2,3,6.7], target=7

可以看到[2,2,3]这一组符合条件,还有[7]符合条件。那么就可以写出如下代码。

class Solution {
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        List<List<Integer>> res = new ArrayList<>();
        
        Deque<Integer> path = new ArrayDeque<>();
        dfs(candidates, target, 0, path, res);
        return res;
    }
    
    public void dfs(int[] candidates, int target, int begin, Deque<Integer> path, List<List<Integer>> res) {
        // 退出条件 和 == target
        if (target == 0) {
            res.add(new ArrayList<>(path));
            return;
        }
        else if (target < 0) {
            return;
        }
        
        for (int i = begin; i < candidates.length; i++) {
            path.add(candidates[i]);
          	// 因为可以重复提取元素,所以这里传入的begin依然是i
            dfs(candidates, target - candidates[i], i, path, res);
            path.removeLast();
        }
    }  
}

其实通过图也可以看出,有大量的计算是无效的,比如在得到[2,2,3]这个组合后,依然会去计算[2,2,6][2,2,7]以及更深的递归,这些都造成了浪费,所以需要进行剪枝。

如果对数组进行排序,那么在路径和达到target后,就知道再加上后面的数就会变为负数,不符合要求,可以剪枝,所以新的代码如下。

class Solution {
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        List<List<Integer>> res = new ArrayList<>();
        Arrays.sort(candidates);
        Deque<Integer> path = new ArrayDeque<>();
        dfs(candidates, target, 0, path, res);
        return res;
    }
    
    public void dfs(int[] candidates, int target, int begin, Deque<Integer> path, List<List<Integer>> res) {
        // 退出条件 因为小于0被剪枝,所以不需要再判断
        if (target == 0) {
            res.add(new ArrayList<>(path));
            return;
        }
        
        for (int i = begin; i < candidates.length; i++) {
            if (target - candidates[i] < 0) {
                break;
            }
            path.add(candidates[i]);
            dfs(candidates, target - candidates[i], i, path, res);
            path.removeLast();
        }
    }  
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值