|
5 | 5 |
|
6 | 6 | class Solution:
|
7 | 7 | def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
|
8 |
| - return self.solveWithDFS(candidates, target) |
| 8 | + return self.solveWithBackTracking(candidates, target) |
9 | 9 |
|
10 | 10 | """
|
11 | 11 | Runtime: 2039 ms (Beats 5.01%)
|
@@ -37,12 +37,36 @@ def solveWithDFS(self, candidates: List[int], target: int) -> List[List[int]]:
|
37 | 37 | return result
|
38 | 38 |
|
39 | 39 | """
|
40 |
| - Runtime: ? |
41 |
| -
|
42 |
| - Memory: ? |
| 40 | + Runtime: 58 ms (Beats 32.30%) |
| 41 | + |
| 42 | + - candidates 정렬에 O(log c) |
| 43 | + - 첫 depte에서 dfs 함수 호출에 O(c) |
| 44 | + - 그 후 candidates의 길이에 비례해서 재귀적으로 dfs를 호출하는데 O(c) |
| 45 | + - lower_bound_idx에 따라 range가 감소하기는 하나 일단은 비례 O(c') |
| 46 | + > O(log c) + O(c * c') ~= O(c * c), 단 c' <= c 이므로 이 복잡도는 upper bound |
| 47 | + Memory: 16.59 MB (Beats 75.00%) |
| 48 | + - result를 제외하고 모두 nonlocal 변수를 call by reference로 참조 |
| 49 | + - dfs 함수 호출마다 메모리가 증가하는데, 호출횟수는 candidates의 길이에 비례 O(c) |
| 50 | + - lower_bound_idx에 따라 range가 감소하기는 하나 일단은 비례 |
| 51 | + > O(c), 단 이 복잡도는 upper bound |
43 | 52 | """
|
44 | 53 | def solveWithBackTracking(self, candidates: List[int], target: int) -> List[List[int]]:
|
45 |
| - return [] |
| 54 | + def dfs(stack: List[int], sum: int, lower_bound_idx: int): |
| 55 | + nonlocal result, candidates, target |
| 56 | + |
| 57 | + if target < sum: |
| 58 | + return |
| 59 | + elif sum < target: |
| 60 | + for idx in range(lower_bound_idx, len(candidates)): |
| 61 | + dfs(stack + [candidates[idx]], sum + candidates[idx], idx) |
| 62 | + else: # target == sum |
| 63 | + result.append(stack) |
| 64 | + return |
| 65 | + |
| 66 | + result = [] |
| 67 | + candidates.sort() |
| 68 | + dfs([], 0, 0) |
| 69 | + return result |
46 | 70 |
|
47 | 71 |
|
48 | 72 | class _LeetCodeTestCases(TestCase):
|
|
0 commit comments