MockInterview: 39 Combination Sum
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]
]
pratice code:
class Solution {
public List<List<Integer>> combinationSum(int[] candidates, int target) {
return helper(candidates,target,0);
}
public List<List<Integer>> helper(int[] candidates, int target, int index){
int num = candidates[0];
int i = 1;
List<List<Integer>> res = new ArrayList<List<Integer>>();
while(num*i<target){
List<List<Integer>> sub = helper(candidates, target - num * i, index + 1);
if(sub != null){
for(List<Integer> list: sub){
for(int j = 1; j <= i; j++){
list.add(num);
}
res.add(list);
}
}
for(int j = 1; j <= i; j++){
List<Integer> list = new List<Integer>();
list.add(num);
}
res.add(list);
}
return res;
}
}
Correct Code:
1) need one more arguement for function helper, List<Integer> path keep record of the mediate result, each time add one number, will change the path. at the end of the helper, will remove the number, revert to the original state.
2) only if the remaining target is 0, the path is valid, add its copy to result.
3) void duplicate path, take 2, 3 and 3, 2 for example. the loop only start from start index, it won't get the index smaller than start index.
class Solution {
public List<List<Integer>> combinationSum(int[] candidates, int target) {
List<List<Integer>> res = new ArrayList<List<Integer>>();
List<Integer> path = new ArrayList<Integer>();
Arrays.sort(candidates);
helper(candidates,target,0,res, path);
return res;
}
public void helper(int[] candidates, int target,int index, List<List<Integer>> res, List<Integer> path){
if(target == 0) {
List<Integer> copy = new ArrayList<Integer>(path);
res.add(copy);
return;
}
if(target < 0) return;
for(int i = index; i < candidates.length; i++){
if(candidates[i] > target){break;}
path.add(candidates[i]);
helper(candidates,target-candidates[i],i,res, path);
path.remove(path.size()-1);
}
}
}
Comments
Post a Comment