leetcode Java二刷:39. 组合总和

23 篇文章 0 订阅
11 篇文章 0 订阅

题目:39. 组合总和

思路:回溯

为了方便后续处理,我们先排序。

  • 我们用目标值不断减去放入结果集合的数字,这样目标值与0比较即可判断是否找到解;

  • 加速剪枝:回溯的过程中,如果目标值减去当前数字小于0,那么后面所有数字都不可能满足条件了(已经排序),此时直接返回;

  • 去重剪枝:这道题,数字可以重复使用,去重剪枝包含两块:

    • (1)对于重复的数字,我们只考虑第一个,其余的全部跳过;
    • (2)每一次的搜索都从当前位置开始,不考虑当前位置之前的数字,因为之前的数字已经搜索过了。
      例1:1113,target = 4
      例2:123, target = 5

代码:

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

    }
    public void backtrack(List<List<Integer>> res, List<Integer> cur, int[] candidates, int start, int target) {
        if (0 == target) {
            res.add(new ArrayList<>(cur));
            return;
        }
        for (int i = start; i < candidates.length; i++) {
        	// 剪枝
            if (target - candidates[i] < 0) {
                return;
            }
            // 去重
            if (i - 1 >= 0 && candidates[i] == candidates[i - 1]) {
                continue;
            }
            cur.add(candidates[i]);
            // 数字可以重复使用,所以仍从当前位置i开始搜索。
            backtrack(res, cur, candidates, i, target - candidates[i]);
            cur.remove(cur.size() - 1);
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值