-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCombination-sum-problem.py
76 lines (55 loc) · 1.79 KB
/
Combination-sum-problem.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
# Using recursion
def findWays_recursion(nums, tar):
# Base case: if tar < 0
if tar < 0:
return 0
# Base case: if tar == 0
if tar == 0:
return 1
ans = 0
for i in range(len(nums)):
ans += findWays_recursion(nums, tar - nums[i])
return ans
# Using Top-Down Dynamic Programming (Memoization)
def findWays_memoization(nums, tar, dp):
# Base case: if tar < 0
if tar < 0:
return 0
# Base case: if tar == 0
if tar == 0:
return 1
# Check if the result already computed or not
if dp[tar] != -1:
return dp[tar]
ans = 0
for i in range(len(nums)):
ans += findWays_memoization(nums, tar - nums[i], dp)
dp[tar] = ans
return dp[tar]
# Using Bottom-Up Dynamic Programming (Tabulation)
def findWays_tabulation(nums, tar):
dp = [0] * (tar + 1)
# Base case: if tar < 0 or tar == 0
dp[0] = 1
# traversing from 1 to tar
for i in range(1, tar + 1):
# traversing on nums
for j in range(len(nums)):
if (i - nums[j]) >= 0:
dp[i] += dp[i - nums[j]]
return dp[tar]
"""
Problem statement:
You are given an array of distinct integers.
You have to tell how many different ways of selecting the elements from the arrayare there such that the sum of chosen elements is equal to the target.
"""
if __name__ == '__main__':
tar = 5
array = [1, 2, 5] # output: 9
# Test the recursive function
print(f"Number of ways: {findWays_recursion(array, tar)}\n")
# Test the Top-down DP(Memoization) function
dp = [-1] * (tar + 1)
print(f"Number of ways: {findWays_memoization(array, tar, dp)}\n")
# Test the Bottom-up DP(Tabulation) function
print(f"Number of ways: {findWays_tabulation(array, tar)}\n")