Combination Sum
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.
- 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]
]
Solution: (DP)
public class Solution {
public List<List<Integer>> combinationSum(int[] candidates, int target) {
Arrays.sort(candidates);
HashMap<Integer, ArrayList<List<Integer>>> map = new HashMap<>();
map.put(0,new ArrayList<List<Integer>>());
map.get(0).add(new ArrayList<Integer>());
ArrayList<List<Integer>> sum = new ArrayList<List<Integer>>();
for(int i = 1; i <= target; i++){
sum = new ArrayList<List<Integer>>();
for(int option: candidates){
if(i-option >= 0){
ArrayList<List<Integer>> temp = map.get(i-option);
if(temp != null){
for(List<Integer> t: temp){
List<Integer> t2 = new ArrayList<Integer>();
t2.addAll(t);
t2.add(option);
Collections.sort(t2);
if(!sum.contains(t2)) sum.add(t2);
}
}
}
else break;
}
map.put(i, sum);
}
return sum;
}
}