leetcode39.Combination Sum

题目要求

1
2
3
4
5
6
7
8
9
10
11
12
13
Given a set of candidate numbers (C) (without duplicates) and a target number (T), find all unique combinations in C where the candidate numbers sums to T.

The same repeated number may be chosen from C unlimited number of times.

Note:
All numbers (including target) will be positive integers.
The solution set must not contain duplicate combinations.
For example, given candidate set [2, 3, 6, 7] and target 7,
A solution set is:
[
[7],
[2, 2, 3]
]

一个整数数组,数组中的值不重复,要求在数组中找到所有的子数组,子数组满足元素的和为目标值的条件

思路和代码

这道题目有一个标签是backtracking,即在前一种条件的情况下计算当前条件产生的结果值。在这道题中,我结合了递归的思想来。就是将当前的值作为一个潜在的结果值加入一个结果数组将数组作为当前结果传入下一轮递归。

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
27
28
29
30
31
32
33
34
35
36
37
38
public class CombinationSum_39 {
List<List<Integer>> result = new ArrayList<List<Integer>>();
public List<List<Integer>> combinationSum(int[] candidates, int target) {
Arrays.sort(candidates);

for(int i = 0 ; i<candidates.length ; i++){
if(candidates[i] == target){
result.add(Arrays.asList(candidates[i]));
}else{
List<Integer> temp = new ArrayList<Integer>();
temp.add(candidates[i]);
combinationSum(candidates, i, target-candidates[i], temp);

}
}
return result;
}

public void combinationSum(int[] candidates, int start, int target, List<Integer> currentResult){
for(int i = start ; i < candidates.length ; i++){
if(candidates[i] == target){
currentResult.add(candidates[i]);
result.add(currentResult);
return;
}
if(candidates[i] > target){
return;
}
if(candidates[i] < target){
List<Integer> temp = new ArrayList<Integer>();
temp.addAll(currentResult);
temp.add(candidates[i]);
combinationSum(candidates, i, target-candidates[i], temp);
}
}
}
}