|
1 |
| -Given an integer array with all positive numbers and no duplicates, find the number of possible combinations that add up to a positive integer target. |
| 1 | +""" |
| 2 | +Given an integer array with all positive numbers and no duplicates, |
| 3 | +find the number of possible combinations that |
| 4 | +add up to a positive integer target. |
2 | 5 |
|
3 | 6 | Example:
|
4 | 7 |
|
|
22 | 25 | How does it change the problem?
|
23 | 26 | What limitation we need to add to the question to allow negative numbers?
|
24 | 27 |
|
| 28 | +""" |
25 | 29 |
|
26 |
| -private int[] dp; |
27 |
| - |
28 |
| -public int combinationSum4(int[] nums, int target) { |
29 |
| - dp = new int[target + 1]; |
30 |
| - Arrays.fill(dp, -1); |
31 |
| - dp[0] = 1; |
32 |
| - return helper(nums, target); |
33 |
| -} |
34 |
| - |
35 |
| -private int helper(int[] nums, int target) { |
36 |
| - if (dp[target] != -1) { |
37 |
| - return dp[target]; |
38 |
| - } |
39 |
| - int res = 0; |
40 |
| - for (int i = 0; i < nums.length; i++) { |
41 |
| - if (target >= nums[i]) { |
42 |
| - res += helper(nums, target - nums[i]); |
43 |
| - } |
44 |
| - } |
45 |
| - dp[target] = res; |
46 |
| - return res; |
47 |
| -} |
48 |
| - |
49 |
| - |
50 |
| -EDIT: The above solution is top-down. How about a bottom-up one? |
51 |
| - |
52 |
| -public int combinationSum4(int[] nums, int target) { |
53 |
| - int[] comb = new int[target + 1]; |
54 |
| - comb[0] = 1; |
55 |
| - for (int i = 1; i < comb.length; i++) { |
56 |
| - for (int j = 0; j < nums.length; j++) { |
57 |
| - if (i - nums[j] >= 0) { |
58 |
| - comb[i] += comb[i - nums[j]]; |
59 |
| - } |
60 |
| - } |
61 |
| - } |
62 |
| - return comb[target]; |
63 |
| -} |
| 30 | +dp = None |
| 31 | + |
| 32 | + |
| 33 | +def helper_topdown(nums, target): |
| 34 | + global dp |
| 35 | + if dp[target] != -1: |
| 36 | + return dp[target] |
| 37 | + res = 0 |
| 38 | + for i in range(0, len(nums)): |
| 39 | + if target >= nums[i]: |
| 40 | + res += helper_topdown(nums, target - nums[i]) |
| 41 | + dp[target] = res |
| 42 | + return res |
| 43 | + |
| 44 | + |
| 45 | +def combination_sum_topdown(nums, target): |
| 46 | + global dp |
| 47 | + dp = [-1] * (target + 1) |
| 48 | + dp[0] = 1 |
| 49 | + return helper_topdown(nums, target) |
| 50 | + |
| 51 | + |
| 52 | +# EDIT: The above solution is top-down. How about a bottom-up one? |
| 53 | +def combination_sum_bottom_up(nums, target): |
| 54 | + comb = [0] * (target + 1) |
| 55 | + comb[0] = 1 |
| 56 | + for i in range(0, len(comb)): |
| 57 | + for j in range(len(nums)): |
| 58 | + if i - nums[j] >= 0: |
| 59 | + comb[i] += comb[i - nums[j]] |
| 60 | + return comb[target] |
| 61 | + |
| 62 | + |
| 63 | +combination_sum_topdown([1, 2, 3], 4) |
| 64 | +print dp[4] |
| 65 | + |
| 66 | +print combination_sum_bottom_up([1, 2, 3], 4) |
0 commit comments