0040. 组合总和 II

2021-08-20  本文已影响0人  蓝笔头

题目地址

https://leetcode-cn.com/problems/combination-sum/

题目描述

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

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

说明:

所有数字(包括目标数)都是正整数。
解集不能包含重复的组合。 
示例 1:

输入: candidates = [10,1,2,7,6,1,5], target = 8,
所求解集为:
[
  [1, 7],
  [1, 2, 5],
  [2, 6],
  [1, 1, 6]
]
示例 2:

输入: candidates = [2,5,2,1,2], target = 5,
所求解集为:
[
  [1,2,2],
  [5]
]

题解

回溯算法

解法和 0039. 组合总和 基本一致

class Solution {
    public List<List<Integer>> combinationSum2(int[] candidates, int target) {
        // 先排序
        Arrays.sort(candidates);

        List<Integer> selected = new ArrayList<>();
        List<List<Integer>> results = new ArrayList<>();
        dfs(candidates, target, 0, selected, results);

        return results;
    }

    public void dfs(int[] candidates, int target, int beginIndex, List<Integer> selected, List<List<Integer>> results) {
        if (target < 0) {
            return;
        }

        if (target == 0) {
            results.add(new ArrayList(selected));
            return;
        }

        for (int i = beginIndex; i < candidates.length; ++ i) {
            // 使用 Integer
            // 避免调用 List 调用 remove(int index); 方法
            Integer candidate = candidates[i];

            // 做选择
            selected.add(candidate);

            dfs(candidates, target - candidate, i + 1, selected, results);

            // 撤销选择
            selected.remove(candidate);

            // 如果 candidates[i] == candidates[i + 1],表示当前分支已经走过了
            // 因此要跳过
            while (i + 1 < candidates.length && candidates[i] == candidates[i + 1]) {
                i ++;
            }
        }
    }
}
上一篇 下一篇

猜你喜欢

热点阅读