5
5
6
6
class Solution :
7
7
def combinationSum (self , candidates : List [int ], target : int ) -> List [List [int ]]:
8
- return self .solve_with_dfs (candidates , target )
8
+ return self .solveWithBackTracking (candidates , target )
9
9
10
10
"""
11
11
Runtime: 2039 ms (Beats 5.01%)
12
- Time Complexity: ?
13
-
12
+ Time Complexity: O(c * c * log c)
13
+ - ์ฒ์ stack์ ํฌ๊ธฐ๋ c์ ๋น๋ก O(c)
14
+ - ์ค๋ณต ์ ๊ฑฐ์ ์ฌ์ฉํ๋ ๋ณ์์ธ curr_visited_checker ์์ฑ์ O(c' log c')
15
+ - stack์ ๋ด๋ถ ๋ก์ง์์ c์ ๋น๋กํ for๋ฌธ์ ์ํํ๋๋ฐ O(c)
16
+ > O(c) * O(c' log c') + O(c) * O(c) ~= O(c * c * log c)
17
+
14
18
Memory: 16.81 MB (Beats 11.09%)
15
- Space Complexity: ?
19
+ Space Complexity: O(c * c)
20
+ - curr_combination์ ํฌ๊ธฐ๊ฐ c์ ๋น๋ก
21
+ - stack์ ํฌ๊ธฐ๋ curr_combination์ ํฌ๊ธฐ์ c์ ๋น๋ก
22
+ > O(c * c)
16
23
"""
17
- def solve_with_dfs (self , candidates : List [int ], target : int ) -> List [List [int ]]:
24
+ def solveWithDFS (self , candidates : List [int ], target : int ) -> List [List [int ]]:
18
25
result = []
19
26
stack = []
20
27
visited = defaultdict (bool )
@@ -38,6 +45,38 @@ def solve_with_dfs(self, candidates: List[int], target: int) -> List[List[int]]:
38
45
39
46
return result
40
47
48
+ """
49
+ Runtime: 58 ms (Beats 32.30%)
50
+ Time Complexity: O(c * c)
51
+ - candidates ์ ๋ ฌ์ O(log c)
52
+ - ์ฒซ depte์์ dfs ํจ์ ํธ์ถ์ O(c)
53
+ - ๊ทธ ํ candidates์ ๊ธธ์ด์ ๋น๋กํด์ ์ฌ๊ท์ ์ผ๋ก dfs๋ฅผ ํธ์ถํ๋๋ฐ O(c)
54
+ - lower_bound_idx์ ๋ฐ๋ผ range๊ฐ ๊ฐ์ํ๊ธฐ๋ ํ๋ ์ผ๋จ์ ๋น๋ก O(c')
55
+ > O(log c) + O(c * c') ~= O(c * c), ๋จ c' <= c ์ด๋ฏ๋ก ์ด ๋ณต์ก๋๋ upper bound
56
+ Memory: 16.59 MB (Beats 75.00%)
57
+ Space Complexity: O(c)
58
+ - result๋ฅผ ์ ์ธํ๊ณ ๋ชจ๋ nonlocal ๋ณ์๋ฅผ call by reference๋ก ์ฐธ์กฐ
59
+ - dfs ํจ์ ํธ์ถ๋ง๋ค ๋ฉ๋ชจ๋ฆฌ๊ฐ ์ฆ๊ฐํ๋๋ฐ, ํธ์ถํ์๋ candidates์ ๊ธธ์ด์ ๋น๋ก O(c)
60
+ - lower_bound_idx์ ๋ฐ๋ผ range๊ฐ ๊ฐ์ํ๊ธฐ๋ ํ๋ ์ผ๋จ์ ๋น๋ก
61
+ > O(c), ๋จ ์ด ๋ณต์ก๋๋ upper bound
62
+ """
63
+ def solveWithBackTracking (self , candidates : List [int ], target : int ) -> List [List [int ]]:
64
+ def dfs (stack : List [int ], sum : int , lower_bound_idx : int ):
65
+ nonlocal result , candidates , target
66
+
67
+ if target < sum :
68
+ return
69
+ elif sum < target :
70
+ for idx in range (lower_bound_idx , len (candidates )):
71
+ dfs (stack + [candidates [idx ]], sum + candidates [idx ], idx )
72
+ else : # target == sum
73
+ result .append (stack )
74
+ return
75
+
76
+ result = []
77
+ candidates .sort ()
78
+ dfs ([], 0 , 0 )
79
+ return result
41
80
42
81
class _LeetCodeTestCases (TestCase ):
43
82
def test_1 (self ):
0 commit comments