39. Combination Sum
Given a set of candidate numbers (C) (without duplicates) 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]
]
This is a mutation of subset sum problem. It has pseudo polynomial solution,
which can be done in DP.
The problem can also be asked like: give sum n, and m different valued coins,
how many ways can you make changes from these coins, order does not matter.
The easier version is to just output how many ways. just a few lines.
the idea is the knapsack solution. time complexity O(n*target),space
complexity O(target).
public void combinationSum(int[] candidates, int target) {
int dp[] = new int[target + 1];
dp[0] = 1;
for(int i=0; i> combinationSum(int[] a, int target) {
List
> res = new ArrayList
>();
List
> res) {
if(sum == target) {
res.add(new ArrayList(l));
return;
}
if(sum>target)
return;
for(int j=i; j