Each number in C may only be used once in the combination.
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 10,1,2,7,6,1,5 and target 8,
A solution set is:
[1, 7]
[1, 2, 5]
[2, 6]
[1, 1, 6]
Idea: Depth-first search. First sort the array. Then for each number smaller than the target, e.g. num[i], add it to the path and recursively search for the next target=target - num[i]. Since each number can be used only once, the start index of the recursion is i+1. If the current target==0, means a valid solution is fond. Add it to the result.
Time: O(n!) Space:O(n)
Code:
public class Solution {
public List<List<Integer>> combinationSum2(int[] num, int target) {
List<List<Integer>> result=new ArrayList<List<Integer>>();
if(num==null||num.length==0)
return result;
Arrays.sort(num);
ArrayList<Integer> path=new ArrayList<Integer>();
dfs(num,target,0,path,result);
return result;
}
public void dfs(int[] num,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<num.length;i++)
{
if(num[i]>target)
break;
if(i>start&&num[i]==num[i-1])
continue;
int nextTarget=target-num[i];
path.add(num[i]);
dfs(num,nextTarget,i+1,path,result);
path.remove(path.size()-1);
}
}
}
No comments:
Post a Comment