Skip to content

Commit c772a8a

Browse files
committed
Rewrite combination_sum.py to python from Java
1 parent 9c295e5 commit c772a8a

File tree

1 file changed

+42
-39
lines changed

1 file changed

+42
-39
lines changed

dp/combination_sum.py

Lines changed: 42 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,7 @@
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.
25
36
Example:
47
@@ -22,42 +25,42 @@
2225
How does it change the problem?
2326
What limitation we need to add to the question to allow negative numbers?
2427
28+
"""
2529

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

Comments
 (0)