Given a set of candidate numbers (C) 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.
- Elements in a combination (a1, a2, … , ak) must be in non-descending order. (ie, a1 ≤ a2 ≤ … ≤ ak).
- The solution set must not contain duplicate combinations.
2,3,6,7 and target 7, A solution set is:
[7] [2, 2, 3]
给定数组和目标值,从数组中找到所有的组合,使得组合的总和等于目标值,数组中的值可以重复选取。
这个题目的主要思路就是递归回溯,说来惭愧,好久没写递归,答案还是参考了别人的。
下面是本题的java实现。
public class Solution {
public List<List<Integer>> combinationSum(int[] candidates, int target) {
List<List<Integer>> res = new ArrayList<List<Integer>>();
List<Integer> tmp = new ArrayList<Integer>();
dfs(res,tmp,candidates,target,0);
return res;
}
public void dfs(List<List<Integer>> res,List<Integer> tmp,int[] candidates, int gap,int index){
if(gap == 0){
List<Integer> list = new ArrayList<Integer>(tmp);
res.add(list);
return;
}
for(int i = index ; i < candidates.length; i++){
if(gap < candidates[index])
return;
else{
tmp.add(candidates[i]);
gap -= candidates[i];
dfs(res,tmp,candidates,gap,i);
tmp.remove(tmp.size()-1);
}
}
}
}
3785

被折叠的 条评论
为什么被折叠?



