Number of ways that you can get the target from a list of numbers.
order doesn’t matter
recursion:
public int combinationSum(int[] candidates, int target) {
Arrays.sort(candidates);
int count = 0;
return helper(candidates, 0, target);
}
public int helper(int[] candidates, int position, int target) {
if (target == 0) {
return 1;
} else if (target < 0) {
return 0;
}
for (int i = position; i < candidates.length; i++) {
if (candidates[i] > target) {
continue;
}
return helper(candidates, i, target - candidates[i])
+ helper(candidates, i + 1, target);
}
return 0;
}
dynamic programming method 1:
public int getNumOfWays(int[] inputs, int target) {
if (inputs == null || inputs.length == 0) {
return 0;
}
// 0 1 2 3 4
// 0 1 0 0 0 0
// 1 1 1 1 1 1
// 2 1 0 2
// 3 1
int len = inputs.length;
int[][] table = new int[len + 1][target + 1];
for (int i = 0; i <= target; i++) {
table[0][i] = 0;
}
//target == 0, fill in 1's
for (int i = 0; i <= len; i++) {
table[i][0] = 1;
}
table[0][0] = 1;
for (int i = 1; i <= len; i++) {
for (int j = 1; j <= target; j++) {
if (inputs[i-1] > j) {
table[i][j] = table[i-1][j];
} else {
table[i][j] = table[i - 1][j] + table[i][j - inputs[i - 1]];
}
}
}
return table[len][target];
}
dynamic programming method 2
public class DP {
public int combinationSum(int[] candidates, int target) {
Arrays.sort(candidates);
if (target == 0) {
return 0;
}
int[] table = new int[target + 1];
table[0] = 1;
for (int i = 0; i < candidates.length; i++) {
for (int j = candidates[i]; j <= target; j++) {
table[j] += table[j - candidates[i]];
}
}
return table[target];
}
public static void main(String[] args) {
int[] candidates = {2, 3, 6, 7};
DP test = new DP();
System.out.println(test.combinationSum(candidates, 7));
}
}