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] ]
解题思路:
1. 首先将数组排序,这样比target大的元素就可以直接不用再考虑
2.用一个list记录数字,按照顺序遍历数组,把元素加进list,计算list中元素的和,如果小于target就继续加,如果大于target就舍弃,如果正好等于target就记录这个list
3. 利用递归的思路,将元素加进list之后开始下一轮递归,递归结束后要把加进去的元素remove掉
代码如下:
public class Solution {
private List<List<Integer>> result;
public List<List<Integer>> combinationSum(int[] candidates, int target) {
result = new ArrayList<>();
Arrays.sort(candidates);
findResult(new ArrayList<>(),candidates,0,target);
return result;
}
public void findResult(List<Integer> list,int[] nums,int start,int target){
if(target < 0){
return;
}
else if(target == 0){
result.add(new ArrayList<>(list));
}
else{
for(int i =start;i < nums.length;i++){
list.add(nums[i]);
findResult(list,nums,i,target - nums[i]);
list.remove(list.size() - 1);
}
}
}
}
Given a collection of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T.
Each number in C may only be used once in the combination.
Note:
- All numbers (including target) will be positive integers.
- The solution set must not contain duplicate combinations.
For example, given candidate set [10, 1, 2, 7, 6, 1, 5]
and target 8
,
A solution set is:
[ [1, 7], [1, 2, 5], [2, 6], [1, 1, 6] ]解题思路:
1. 这周有点偷懒,这两道题目思路都是一样的,只是一些细节的要求不太一样
2. 这题的要求是数组的元素可重复,但是每个元素只能用一次,所以在上一题的基础上要稍作修改,要在循环中把数组中重复的元素跳过,否则会出现重复的结果,然后进行递归的时候,开始递归的元素要后移一位,因为一个元素只能用一次
代码如下:
public class Solution {
private List<List<Integer>> result;
public List<List<Integer>> combinationSum2(int[] candidates, int target) {
result = new ArrayList<>();
Arrays.sort(candidates);
findResult(new ArrayList<>(),candidates,0,target);
return result;
}
public void findResult(List<Integer> list,int[] nums,int start,int target){
if(target < 0){
return;
}
else if(target == 0){
result.add(new ArrayList<>(list));
}
else{
for(int i =start;i < nums.length;i++){
if(i > start && nums[i] == nums[i-1]){
continue;
}
list.add(nums[i]);
findResult(list,nums,i+1,target - nums[i]);
list.remove(list.size() - 1);
}
}
}
}