LeetCode 40. 组合总和 II

题目描述

🔥 40. 组合总和 II

思路分析

思路描述

参考代码

1
write your code here

🍏 点击查看 Java 题解

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class Solution {
    public List<List<Integer>> combinationSum2(int[] candidates, int target) {
        List<List<Integer>> res = new ArrayList<>();
        Arrays.sort(candidates);
        backtrack(candidates, target, new ArrayList<>(), res, 0);
        return res;
    }

    public void backtrack(int[] candidates, int pathSum, List<Integer> path, List<List<Integer>> res, int start) {
        if (pathSum == 0) {
            res.add(new ArrayList<>(path)); // 找到一个组合,加入结果集
            return;
        } else if (pathSum < 0) { // 剪枝,如果 pathSum 小于 0,说明当前组合不合法,直接返回
            return;
        }
        for (int i = start; i < candidates.length; i++) {
            if (i > start && candidates[i] == candidates[i - 1]) { // 去重,跳过重复的元素
                continue;
            }
            path.add(candidates[i]);
            backtrack(candidates, pathSum - candidates[i], path, res, i + 1);
            path.remove(path.size() - 1);
        }
    }
}

相似题目

题目 难度 题解
组合总和 Medium  
本文作者:
本文链接: https://hgnulb.github.io/blog/90779862
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议,转载请注明出处!