Leetcode 40 组合总数II

18 篇文章 0 订阅
题目

给定一个数组 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。

candidates 中的每个数字在每个组合中只能使用一次。

注意:解集不能包含重复的组合。

解题思路

  这题跟39题差不多,同样是递归+回溯,方法不再赘述。与39题不同的是,此题的数字仅能使用一次,而且有重复数字,那么就需要考虑去重,直接用 Set 保存的话,亲测会TLE。先对数组排序,在考虑下一个数的时候,需要判断当前元素是否与前一个元素相同,如果相同而且前一个元素没被用过,那么它本身也不用被考虑。因为如果相同的数前一个数没被用过,说明已经完成回溯的过程,即这个数的值已经被考虑过,再判断就是重复情况了。此题判断数组元素用没用过,用了一个 flag 数组。

代码
class Solution {
    public boolean[] flag;

    public List<List<Integer>> combinationSum2(int[] candidates, int target) {
        Arrays.sort(candidates);
        flag = new boolean[candidates.length];
        List<List<Integer>> ans = new ArrayList<>();
        dfs(candidates, target, 0, new ArrayList<>(), ans);
        return new ArrayList<>(ans);
    }

    private void dfs(int[] candidates, int target, int beginIndex, ArrayList<Integer> now, List<List<Integer>> ans) {
        if (target == 0) {
            ans.add(new ArrayList<>(now));
            return;
        }
        int length = candidates.length;
        for (int i = beginIndex; i < length; i++) {
            if (i > 0 && candidates[i - 1] == candidates[i] && !flag[i - 1]) continue;
            if (flag[i]) continue;
            if (candidates[i] > target) break;
            flag[i] = true;
            now.add(candidates[i]);
            dfs(candidates, target - candidates[i], i + 1, new ArrayList<>(now), ans);
            flag[i] = false;
            now.remove(now.size() - 1);
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值