题目
Given a set of candidate numbers (
candidates
) (without duplicates) and a target number (target
), find all unique combinations incandidates
where the candidate numbers sums totarget
.The same repeated number may be chosen from
candidates
unlimited number of times.Note:
- All numbers (including
target
) will be positive integers.- The solution set must not contain duplicate combinations.
Example 1:
Input: candidates =[2,3,6,7],
target =7
, A solution set is: [ [7], [2,2,3] ]Example 2:
Input: candidates = [2,3,5] target = 8, A solution set is: [ [2,2,2,2], [2,3,3], [3,5] ]
解题思路
本题要求给出一个数组和一个目标的值,在数组中选择n个数字,得到所有可以相加等于目标值得情况,且结果的集合中不可以存在重复的组合。
这很显然是要对所有的情况进行遍历,在遍历的过程中,得到所有符合条件的集合放入到结果集中。本人对于递归相关的解法掌握的不好,所以参考率前人提交的解法,选出了两种解法和大家分享
代码实现
1、递归方式
public class Solution {
public List<List<Integer>> combinationSum(int[] candidates, int target) {
Arrays.sort(candidates);
List<List<Integer>> result = new ArrayList<List<Integer>>();
getResult(result, new ArrayList<Integer>(), candidates, target, 0);
return result;
}
private void getResult(List<List<Integer>> result, List<Integer> cur, int candidates[], int target, int start){
if(target > 0){
for(int i = start; i < candidates.length && target >= candidates[i]; i++){
cur.add(candidates[i]);
getResult(result, cur, candidates, target - candidates[i], i);
cur.remove(cur.size() - 1);
}//for
}//if
else if(target == 0 ){
result.add(new ArrayList<Integer>(cur));
}//else if
}
}
2、非递归方式
public List<List<Integer>> combinationSum(int[] candidates, int target) {
Arrays.sort(candidates);
int i=0, size = candidates.length, sum=0;
Stack<Integer> combi = new Stack<>(), indices = new Stack<>();
List<List<Integer>> result = new ArrayList<>();
while (i < size) {
if (sum + candidates[i]>= target) {
if (sum + candidates[i] == target) {
combi.push(candidates[i]);
result.add(new ArrayList<>(combi));
combi.pop();
}
// indices stack and combination stack should have the same size all the time
if (!indices.empty()){
sum -= combi.pop();
i = indices.pop();
while (i == size-1 && !indices.empty()) {
i = indices.pop();
sum -= combi.pop();
}
}
i++;
} else {
combi.push(candidates[i]);
sum +=candidates[i];
indices.push(i);
}
}
return result;
}