40. Combination Sum II

题目分析

找出一个数组若干数的和等于 target 的所有可行解,每个元素只能使用一次 + 回溯法

代码

class Solution {
    public List> combinationSum2(int[] candidates, int target) {
     List> res = new ArrayList<>();
        if(candidates == null || candidates.length == 0) return res;
        List combination = new ArrayList<>();
        Arrays.sort(candidates);
        helper(res, candidates, combination, 0, target);
        return res;
    }
    public void helper(List> res, int[] candidates, List combination, int index, int target) {
        // 寻找到了目标解
        if(target == 0) {
            res.add(new ArrayList(combination));
            return;
        }
        for(int i = index; i < candidates.length; i++) { 
            if(candidates[i] > target) {
                break;
            }
            // 去重
            if(i != index && candidates[i] == candidates[i - 1]) {
                continue;
            }
            
            combination.add(candidates[i]);
            // 与 39 题  Combination Sum 的区别就在这里,i + 1,不重复选取一个元素即可
            helper(res, candidates, combination, i + 1, target - candidates[i]);
            // helper 执行完了,要么是已经添加了可行解不满足条件,回溯
            combination.remove(combination.size() - 1);
        }
    }
}

你可能感兴趣的:(40. Combination Sum II)