39. 组合总和

39. 组合总和

leetcode 39. 组合总和


题目:39. 组合总和

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

candidates 中的数字可以无限制重复被选取。

说明:

  • 所有数字(包括 target)都是正整数。
  • 解集不能包含重复的组合。

示例1:

输入: candidates = [2,3,6,7], target = 7
所求解集为:
[
[7],
[2,2,3]
]

示例2:

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

提示:

  • 1 <= candidates.length <= 30
  • 1 <= candidates[i] <= 200
  • candidate 中的每个元素都是独一无二的。
  • 1 <= target <= 500

方法:Backtracking(回溯)

思路:Backtracking(回溯),经典回溯问题,由于元素可重复选择,每次回溯后重新选择该位置元素时,从上一次回溯开始选择的元素开始。

运行数据:执行用时:2 ms,内存消耗:40.1 MB

复杂度分析:

  • 时间复杂度:O(n * 2^n),n为candidates中元素的个数,生成所有子集的时间复杂度O(2^n),复制到输出集合中的时间复杂度O(n)。
  • 空间复杂度:O(n),n为为candidates中元素的个数,回溯递归时保存临时组合。
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
26
// LeetCode指定调用方法 
public List<List<Integer>> combinationSum(int[] candidates, int target) {

List<List<Integer>> result = new ArrayList<List<Integer>>();

backtracking(candidates, target, result, new ArrayList<>(), 0);

return result;
}

// 回溯,记录当前candidates的开始位置
private void backtracking(int[] candidates, int target, List<List<Integer>> result, List<Integer> combinationSumList, int t) {

if (target == 0) {
result.add(new ArrayList<>(combinationSumList));
return ;
}

for (int i = t; i < candidates.length; i++) {
if (candidates[i] <= target) {
combinationSumList.add(candidates[i]);
backtracking(candidates, target - candidates[i], result, combinationSumList, i);
combinationSumList.remove(combinationSumList.size() - 1);
}
}
}

学习所得,资料、图片部分来源于网络,如有侵权,请联系本人删除。

才疏学浅,若有错误或不当之处,可批评指正,还请见谅!


 
Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×