0
点赞
收藏
分享

微信扫一扫

40.组合总和II

愚鱼看书说故事 2022-03-30 阅读 86

题目

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

candidates 中的每个数字在每个组合中只能使用 一次 。
示例:
在这里插入图片描述

代码

注意去重

class Solution {
    List<List<Integer>> result = new ArrayList<>();
    LinkedList<Integer> path = new LinkedList<>();
    int sum = 0;
    public List<List<Integer>> combinationSum2(int[] candidates, int target) {
        Arrays.sort(candidates);

        backTracing(candidates,target,0);
        return result;

    }

    public void backTracing(int[] candidates,int target,int startIndex){
        if(sum > target){
            return;
        }
        if(sum == target){
            result.add(new ArrayList<Integer>(path));
            return;
        }

        for(int i = startIndex; i < candidates.length; i++){
            //去重
            if(i>startIndex && candidates[i]==candidates[i-1])
            {
                continue;
            }
            sum = sum + candidates[i];
            path.add(candidates[i]);
            backTracing(candidates,target,i+1);
            sum = sum - candidates[i];
            path.removeLast();
        }
    }
}
举报

相关推荐

0 条评论