29.Combination Sum(和为sum的组合)
Level:
Medium
题目描述:
Given a set of candidate numbers (candidates
) (without duplicates) and a target number (target
), find all unique combinations in candidates
where the candidate numbers sums to target
.
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]
]
思路分析:
先对数组进行排序,方便后面递归回溯的过程中进行剪枝。然后设置一个变量sum,记录当前序列的数字和,如果sum的值等于target那么当前序列就是结果的一种,我们利用回溯的思想,找出所有满足要求得解。
代码:
public class Solution{
List<List<Integer>>res=new ArrayList<>();
public List<List<Integer>>combinationSum(int []candidates,int target){
if(candidates==null||candidates.length==0)
return res;
Arrays.sort(candidates);//排序,方便后面剪枝
find(candidates,0,0,target,new ArrayList<>());
return res;
}
public void find(int[]candidates,int start,int sum,int target,ArrayList<Integer>list){
if(sum==target){
res.add(new ArrayList<Integer>(list));
return;
}
for(int i=start;i<candidates.length;i++){
if(sum+candidates[i]<=target){
list.add(candidates[i]);
find(candidates,i,sum+candidates[i],target,list);
list.remove(Integer.valueOf(candidates[i]));
}else{
break; //剪枝
}
}
}
}