|
| 1 | +def generate_sublists_recursive(lst: list[int]) -> list[list[int]]: |
| 2 | + """ |
| 3 | + Generate all sublists of the given list, including the empty sublist using a recursive approach. |
| 4 | +
|
| 5 | + >>> generate_sublists_recursive([1, 2, 3]) |
| 6 | + [[], [1], [1, 2], [1, 2, 3], [2], [2, 3], [3]] |
| 7 | + """ |
| 8 | + def helper(start: int) -> None: |
| 9 | + if start == len(lst): |
| 10 | + return |
| 11 | + for end in range(start + 1, len(lst) + 1): |
| 12 | + result.append(lst[start:end]) |
| 13 | + helper(start + 1) |
| 14 | + |
| 15 | + result: list[list[int]] = [[]] |
| 16 | + helper(0) |
| 17 | + return result |
| 18 | + |
| 19 | + |
| 20 | +def generate_sublists_backtrack(lst: list[int]) -> list[list[int]]: |
| 21 | + """ |
| 22 | + Generate all sublists of the given list, including the empty sublist using a backtracking approach. |
| 23 | +
|
| 24 | + >>> generate_sublists_backtrack([1, 2, 3]) |
| 25 | + [[], [1], [1, 2], [1, 2, 3], [2], [2, 3], [3]] |
| 26 | + """ |
| 27 | + def backtrack(start: int, current: list[int]) -> None: |
| 28 | + result.append(current[:]) |
| 29 | + for end in range(start, len(lst)): |
| 30 | + current.append(lst[end]) |
| 31 | + backtrack(end + 1, current) |
| 32 | + current.pop() |
| 33 | + |
| 34 | + result: list[list[int]] = [] |
| 35 | + backtrack(0, []) |
| 36 | + return result |
| 37 | + |
| 38 | + |
| 39 | +if __name__ == "__main__": |
| 40 | + import doctest |
| 41 | + |
| 42 | + print(generate_sublists_recursive([1, 2, 3])) |
| 43 | + print(generate_sublists_backtrack([1, 2, 3])) |
| 44 | + doctest.testmod() |
0 commit comments