Skip to content

Commit 62257ef

Browse files
authored
Add recursive solution for Subset Sum Problem
1 parent 03a4251 commit 62257ef

File tree

1 file changed

+22
-0
lines changed

1 file changed

+22
-0
lines changed

knapsack/subset_sum_using_recursion

+22
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
def is_subset_sum_recursive(arr, n, target):
2+
# Base cases
3+
if target == 0:
4+
return True # A subset with sum 0 always exists (empty subset)
5+
if n == 0:
6+
return False # No elements left to form the sum
7+
8+
# If the current element is greater than the target, ignore it
9+
if arr[n-1] > target:
10+
return is_subset_sum_recursive(arr, n-1, target)
11+
12+
# Otherwise, check if sum can be obtained by including or excluding the current element
13+
return (is_subset_sum_recursive(arr, n-1, target) or
14+
is_subset_sum_recursive(arr, n-1, target - arr[n-1]))
15+
16+
arr = [3, 34, 4, 12, 5, 2]
17+
target = 9
18+
result = is_subset_sum_recursive(arr, len(arr), target)
19+
print(f"Subset with sum {target} {'exists' if result else 'does not exist'}")
20+
21+
Time Complexity: O(2^N)
22+
Space Complexity: O()

0 commit comments

Comments
 (0)