|
| 1 | +from typing import List |
| 2 | +from unittest import TestCase, main |
| 3 | +from collections import defaultdict |
| 4 | + |
| 5 | + |
| 6 | +class Solution: |
| 7 | + def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]: |
| 8 | + return self.solve_with_dfs(candidates, target) |
| 9 | + |
| 10 | + """ |
| 11 | + Runtime: 2039 ms (Beats 5.01%) |
| 12 | + Time Complexity: ? |
| 13 | +
|
| 14 | + Memory: 16.81 MB (Beats 11.09%) |
| 15 | + Space Complexity: ? |
| 16 | + """ |
| 17 | + def solve_with_dfs(self, candidates: List[int], target: int) -> List[List[int]]: |
| 18 | + result = [] |
| 19 | + stack = [] |
| 20 | + visited = defaultdict(bool) |
| 21 | + for candidate in candidates: |
| 22 | + stack.append([[candidate], candidate]) |
| 23 | + |
| 24 | + while stack: |
| 25 | + curr_combination, curr_sum = stack.pop() |
| 26 | + curr_visited_checker = tuple(sorted(curr_combination)) |
| 27 | + |
| 28 | + if curr_sum == target and visited[curr_visited_checker] is False: |
| 29 | + visited[curr_visited_checker] = True |
| 30 | + result.append(curr_combination) |
| 31 | + |
| 32 | + if target < curr_sum: |
| 33 | + continue |
| 34 | + |
| 35 | + for candidate in candidates: |
| 36 | + post_combination, post_sum = curr_combination + [candidate], curr_sum + candidate |
| 37 | + stack.append([post_combination, post_sum]) |
| 38 | + |
| 39 | + return result |
| 40 | + |
| 41 | + |
| 42 | +class _LeetCodeTestCases(TestCase): |
| 43 | + def test_1(self): |
| 44 | + candidates = [2, 3, 6, 7] |
| 45 | + target = 7 |
| 46 | + output = [[2, 2, 3], [7]] |
| 47 | + self.assertEqual(Solution.combinationSum(Solution(), candidates, target), output) |
| 48 | + |
| 49 | + def test_2(self): |
| 50 | + candidates = [2, 3, 5] |
| 51 | + target = 8 |
| 52 | + output = [[2, 2, 2, 2], [2, 3, 3], [3, 5]] |
| 53 | + self.assertEqual(Solution.combinationSum(Solution(), candidates, target), output) |
| 54 | + |
| 55 | + def test_3(self): |
| 56 | + candidates = [2] |
| 57 | + target = 1 |
| 58 | + output = [] |
| 59 | + self.assertEqual(Solution.combinationSum(Solution(), candidates, target), output) |
| 60 | + |
| 61 | + |
| 62 | +if __name__ == '__main__': |
| 63 | + main() |
0 commit comments