Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit ed4734a

Browse files
authoredOct 23, 2024··
Create subset_sum_dp.py
1 parent 6e24935 commit ed4734a

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed
 

‎knapsack/subset_sum_dp.py

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
def is_subset_sum_dp(arr, target):
2+
# length
3+
n = len(arr)
4+
5+
# (n+1) x (target+1) DP table
6+
dp = []
7+
for i in range(n + 1):
8+
row = []
9+
for j in range(target + 1):
10+
row.append(False)
11+
dp.append(row)
12+
13+
# Initialize the table: If target is 0, answer is True
14+
for i in range(n + 1):
15+
dp[i][0] = True
16+
17+
# Fill the DP table
18+
for i in range(1, n + 1):
19+
for j in range(1, target + 1):
20+
if arr[i-1] > j:
21+
dp[i][j] = dp[i-1][j]
22+
else:
23+
dp[i][j] = dp[i-1][j] or dp[i-1][j - arr[i-1]]
24+
25+
return dp[n][target]
26+
27+
# Test cases
28+
arr = [3, 34, 4, 12, 5, 2]
29+
target = 9
30+
print(is_subset_sum_dp(arr, target)) # Output: True
31+
32+
arr = [3, 34, 4, 12, 5, 2]
33+
target = 30
34+
print(is_subset_sum_dp(arr, target)) # Output: False

0 commit comments

Comments
 (0)
Please sign in to comment.