Skip to content
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 35 additions & 0 deletions knapsack/subset_sum_dp.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
def is_subset_sum_dp(arr, target):
# length
n = len(arr)

# (n+1) x (target+1) DP table
dp = []
for i in range(n + 1):

Check failure on line 7 in knapsack/subset_sum_dp.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (B007)

knapsack/subset_sum_dp.py:7:9: B007 Loop control variable `i` not used within loop body
row = []
for j in range(target + 1):

Check failure on line 9 in knapsack/subset_sum_dp.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (B007)

knapsack/subset_sum_dp.py:9:13: B007 Loop control variable `j` not used within loop body
row.append(False)
dp.append(row)

# Initialize the table: If target is 0, answer is True
for i in range(n + 1):
dp[i][0] = True

# Fill the DP table
for i in range(1, n + 1):
for j in range(1, target + 1):
if arr[i - 1] > j:
dp[i][j] = dp[i - 1][j]
else:
dp[i][j] = dp[i - 1][j] or dp[i - 1][j - arr[i - 1]]

return dp[n][target]


# Test cases
arr = [3, 34, 4, 12, 5, 2]
target = 9
print(is_subset_sum_dp(arr, target)) # Output: True

arr = [3, 34, 4, 12, 5, 2]
target = 30
print(is_subset_sum_dp(arr, target)) # Output: False
Loading