Combination Sum
Source
Given a set of candidate numbers (C) 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.
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]
Java
public class Solution {
public List<List<Integer>> combinationSum(int[] candidates, int target) {
List<List<Integer>> result = new ArrayList<List<Integer>>();
Arrays.sort(candidates);
dfs(candidates, target, 0, new ArrayList<Integer>(), result);
return result;
}
public void dfs(int[] candidates, int target, int pos, List<Integer> path, List<List<Integer>> result){
if(target<0) return;
if(target==0){
result.add(new ArrayList<Integer>(path));
return;
}
for(int i=pos; i<candidates.length; i++){
path.add(candidates[i]);
dfs(candidates, target-candidates[i], i, path, result);
path.remove(path.size()-1);
}
}
}
Python
class Solution(object):
def combinationSum(self, candidates, target):
"""
:type candidates: List[int]
:type target: int
:rtype: List[List[int]]
"""
result=[]
candidates.sort()
self.dfs(candidates, target, 0, [], result)
return result
def dfs(self, candidates, target, pos, path, result):
if target<0:
return
if target==0:
result.append(path[:])
return
for i in range(pos, len(candidates)):
path.append(candidates[i])
self.dfs(candidates, target-candidates[i], i, path, result)
path.pop()