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. >>> path = [] >>> resu
(
nums: list[int],
max_sum: int,
num_index: int,
path: list[int],
result: list[list[int]],
remaining_nums_sum: int,
)
| 30 | |
| 31 | |
| 32 | def create_state_space_tree( |
| 33 | nums: list[int], |
| 34 | max_sum: int, |
| 35 | num_index: int, |
| 36 | path: list[int], |
| 37 | result: list[list[int]], |
| 38 | remaining_nums_sum: int, |
| 39 | ) -> None: |
| 40 | """ |
| 41 | Creates a state space tree to iterate through each branch using DFS. |
| 42 | It terminates the branching of a node when any of the two conditions |
| 43 | given below satisfy. |
| 44 | This algorithm follows depth-fist-search and backtracks when the node is not |
| 45 | branchable. |
| 46 | |
| 47 | >>> path = [] |
| 48 | >>> result = [] |
| 49 | >>> create_state_space_tree( |
| 50 | ... nums=[1], |
| 51 | ... max_sum=1, |
| 52 | ... num_index=0, |
| 53 | ... path=path, |
| 54 | ... result=result, |
| 55 | ... remaining_nums_sum=1) |
| 56 | >>> path |
| 57 | [] |
| 58 | >>> result |
| 59 | [[1]] |
| 60 | """ |
| 61 | |
| 62 | if sum(path) > max_sum or (remaining_nums_sum + sum(path)) < max_sum: |
| 63 | return |
| 64 | if sum(path) == max_sum: |
| 65 | result.append(path) |
| 66 | return |
| 67 | for index in range(num_index, len(nums)): |
| 68 | create_state_space_tree( |
| 69 | nums, |
| 70 | max_sum, |
| 71 | index + 1, |
| 72 | [*path, nums[index]], |
| 73 | result, |
| 74 | remaining_nums_sum - nums[index], |
| 75 | ) |
| 76 | |
| 77 | |
| 78 | if __name__ == "__main__": |
no test coverage detected