forked from ghostmkg/dsa-code
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDsa_sum
More file actions
29 lines (22 loc) · 753 Bytes
/
Dsa_sum
File metadata and controls
29 lines (22 loc) · 753 Bytes
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
def subset_sum(nums, target):
result = []
def backtrack(start, path, current_sum):
# If current sum equals target, record this subset
if current_sum == target:
result.append(path[:])
return
# If sum exceeds target, stop exploring further
if current_sum > target:
return
# Try adding each remaining element
for i in range(start, len(nums)):
path.append(nums[i])
backtrack(i + 1, path, current_sum + nums[i])
path.pop()
backtrack(0, [], 0)
return result
# Example
nums = [3, 4, 5, 2]
target = 7
solutions = subset_sum(nums, target)
print("Subsets that sum to", target, "are:", solutions)