forked from TheAlgorithms/Python
-
Notifications
You must be signed in to change notification settings - Fork 0
/
sum_of_subsets.py
66 lines (55 loc) · 1.74 KB
/
sum_of_subsets.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
"""
The sum-of-subsetsproblem states that a set of non-negative integers, and a
value M, determine all possible subsets of the given set whose summation sum
equal to given M.
Summation of the chosen numbers must be equal to given number M and one number
can be used only once.
"""
from __future__ import annotations
def generate_sum_of_subsets_soln(nums: list[int], max_sum: int) -> list[list[int]]:
result: list[list[int]] = []
path: list[int] = []
num_index = 0
remaining_nums_sum = sum(nums)
create_state_space_tree(nums, max_sum, num_index, path, result, remaining_nums_sum)
return result
def create_state_space_tree(
nums: list[int],
max_sum: int,
num_index: int,
path: list[int],
result: list[list[int]],
remaining_nums_sum: int,
) -> None:
"""
Creates a state space tree to iterate through each branch using DFS.
It terminates the branching of a node when any of the two conditions
given below satisfy.
This algorithm follows depth-fist-search and backtracks when the node is not
branchable.
"""
if sum(path) > max_sum or (remaining_nums_sum + sum(path)) < max_sum:
return
if sum(path) == max_sum:
result.append(path)
return
for index in range(num_index, len(nums)):
create_state_space_tree(
nums,
max_sum,
index + 1,
[*path, nums[index]],
result,
remaining_nums_sum - nums[index],
)
"""
remove the comment to take an input from the user
print("Enter the elements")
nums = list(map(int, input().split()))
print("Enter max_sum sum")
max_sum = int(input())
"""
nums = [3, 34, 4, 12, 5, 2]
max_sum = 9
result = generate_sum_of_subsets_soln(nums, max_sum)
print(*result)