LeetCode39.组合总和II

代码(未剪枝)

class Solution {
    List<List<Integer>> res = new ArrayList<>();
    List<Integer> path = new ArrayList<>();

    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        Arrays.sort(candidates);
        backtracking(candidates, target, 0, 0);
        return res;
    }

    public void backtracking(int[] candidates, int target, int sum, int startIndex) {
        if (sum > target) return;
        if (sum == target) res.add(new ArrayList<>(path));
        for (int i = startIndex; i <= candidates.length - 1; i ++) {
            sum += candidates[i];
            path.add(candidates[i]);
            backtracking(candidates, target, sum, i);
            path.remove(path.size() - 1);
            sum -= candidates[i];
        }
    }
}
posted @ 2022-05-16 11:31  Ac_c0mpany丶  阅读(18)  评论(0)    收藏  举报