Leetcode:40. 组合总和 II

Leetcode: 40. 组合总和 II

题目描述

给定一个数组 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]
]

思路

思路1: DFS+剪枝

与lc39类似,但是每个数只能出现一次,所以节点数量为当前位置+1到最后位置,同时,要避免同一层相同元素,避免出现重复结果(因为会选到),所以可以通过剪枝去除

代码

代码1

class Solution {
    List> results;
    public List> combinationSum2(int[] candidates, int target) {
        results = new ArrayList<>();
        if (candidates == null || candidates.length == 0){
            return results;
        }
        Arrays.sort(candidates);
        List result = new ArrayList();
        dfs(candidates, target, 0, result);
        return results;
    }

    private void dfs(int[] candidates, int target, int idx, List result){
        if (target == 0){
            this.results.add(new ArrayList<>(result));
        }
        
        for(int i = idx; i < candidates.length; i++){
            if (target < 0){
                break;
            }
            if (i > idx && candidates[i] == candidates[i - 1]){
                continue;
            }
            result.add(candidates[i]);
            dfs(candidates, target - candidates[i], i + 1, result);
            result.remove(result.size() - 1);
        }
    }
}

复杂度分析

思路1时间复杂度

$O(n!)$

思路1空间复杂度

$O(n!)$


文章作者: 小风雷
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 小风雷 !
评论
 上一篇
Leetcode:42. 接雨水 Leetcode:42. 接雨水
Leetcode:42. 接雨水题目描述给定 n 个非负整数表示每个宽度为 1 的柱子的高度图,计算按此排列的柱子,下雨之后能接多少雨水。 上面是由数组 [0,1,0,2,1,0,1,3,2,1,2,1] 表示的高度图,在这种情况下,可以接
2020-06-29
下一篇 
Leetcode:39. 组合总和 Leetcode:39. 组合总和
[Leetcode](Leetcode: 39. 组合总和)题目描述给定一个无重复元素的数组 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。 candidate
2020-06-07
  目录