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.
For example, given candidate set 2,3,6,7 and target 7,
A solution set is:
[7]
[2, 2, 3]
Idea: Depth-first search. First sort the array. Then for each of the numbers, e.g. num[i], smaller than the target, add num[i] to the path and recursively find the next target=target-num[i]. Since each element can be used unlimited number of times, the next start index is the same as the current i. If the next target==0, means this is a valid path (a solution), add it to the result.
Time: O(n^n) (actually O(n!)) Space: O(n)
Code:
public class Solution {
public List<List<Integer>> combinationSum(int[] candidates, int target) {
List<List<Integer>> result=new ArrayList<List<Integer>>();
if(candidates.length==0)
return result;
Arrays.sort(candidates);
ArrayList<Integer> path=new ArrayList<Integer>();
dfs(candidates,target,0,path,result);
return result;
}
public void dfs(int[] nums,int target,int start,ArrayList<Integer> path,List<List<Integer>>result)
{
if(target==0)
{
result.add(new ArrayList<Integer>(path));
return;
}
for(int i=start;i<nums.length;i++)
{
if(nums[i]>target)
break;
if(i>start&&nums[i]==nums[i-1])
continue;
int nextTarget=target-nums[i];
path.add(nums[i]);
dfs(nums,nextTarget,i,path,result);
path.remove(path.size()-1);
}
}
}
No comments:
Post a Comment