55
66class Solution :
77 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 )
99
1010 """
1111 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+
1418 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)
1623 """
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 ]]:
1825 result = []
1926 stack = []
2027 visited = defaultdict (bool )
@@ -38,6 +45,38 @@ def solve_with_dfs(self, candidates: List[int], target: int) -> List[List[int]]:
3845
3946 return result
4047
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
4180
4281class _LeetCodeTestCases (TestCase ):
4382 def test_1 (self ):
0 commit comments