File tree Expand file tree Collapse file tree 1 file changed +41
-0
lines changed Expand file tree Collapse file tree 1 file changed +41
-0
lines changed Original file line number Diff line number Diff line change
1
+ class Solution :
2
+ def combinationSum (self , candidates : List [int ], target : int ) -> List [List [int ]]:
3
+ """
4
+ Intuition:
5
+ ๋ฆฌ์คํธ์ ๊ฐ ์์๋ ์ค๋ณตํด์ ์ฌ์ฉํ ์ ์๋ค.
6
+ ๊ทธ๋ ๋ค๋ฉด target์ ์ฌ๊ท์ ์ผ๋ก ์์๋ฅผ ์ฌ์ฉํด์
7
+ ๋ชจ๋ ๊ฒฝ์ฐ์ ์๋ฅผ ํ์ํ๋ค.
8
+
9
+ Time Complexity:
10
+ O(N^2 log N):
11
+ ์ด๊ธฐ์ ๋ฆฌ์คํธ์ ์์๋ฅผ ์ ๋ ฌํ๋ ๋ฐ์ O(N log N)์ด ์์๋๋ค.
12
+ ๋ํ, ์ฌ๊ท ํจ์๋ ์ต๋ N๋ฒ ํธ์ถ๋ ์ ์์ผ๋ฉฐ
13
+ ๊ฐ ์ฌ๊ท ํจ์์์๋ ์ ๋ ฌํ์ฌ ์ธํธ์ ์ถ๊ฐํ๋ ๊ฒฝ์ฐ
14
+ O(N log N)์ด ์์๋๊ณ ,
15
+ N๊ฐ์ ์์์ ๋ํด for๋ฌธ์ ๋ฐ๋ณตํ๋ค.
16
+ ๋ฐ๋ผ์ O(N^2 log N)์ ์๊ฐ๋ณต์ก๋๊ฐ ์์๋๋ค.
17
+
18
+ Space Complexity:
19
+ O(N):
20
+ ์ต์
์ ๊ฒฝ์ฐ answer set์ ๋๋ต N๊ฐ์ tuple์ด ์ ์ฅ๋๋ค.
21
+ ๋ฐ๋ผ์ O(N)์ ๊ณต๊ฐ๋ณต์ก๋๊ฐ ์์๋๋ค.
22
+ """
23
+ candidates .sort () # O(N log N)
24
+ answer_set = set ()
25
+
26
+
27
+ def dfs (n , arr ):
28
+ if n == 0 :
29
+ answer_set .add (tuple (sorted (arr ))) # O(N log N)
30
+ return
31
+
32
+ for candidate in candidates : # O(N)
33
+ if n >= candidate :
34
+ arr .append (candidate )
35
+ dfs (n - candidate , arr )
36
+ arr .pop ()
37
+
38
+
39
+ dfs (target , []) # O(N)
40
+ answer = list (answer_set )
41
+ return answer
You canโt perform that action at this time.
0 commit comments