File tree Expand file tree Collapse file tree 1 file changed +44
-0
lines changed
Expand file tree Collapse file tree 1 file changed +44
-0
lines changed Original file line number Diff line number Diff line change 1+ /**
2+ * Combination Sum
3+ *
4+ * ํต์ฌ ์์ด๋์ด:
5+ * - DFS + ๋ฐฑํธ๋ํน์ผ๋ก ๋ชจ๋ ์กฐํฉ ํ์
6+ * - ๊ฐ์ ์ซ์๋ฅผ ์ฌ๋ฌ ๋ฒ ์ฌ์ฉ ๊ฐ๋ฅ
7+ * - start ์ธ๋ฑ์ค๋ก ์ค๋ณต ์กฐํฉ ๋ฐฉ์ง ([2,3]๊ณผ [3,2] ๊ฐ์ ๊ฒ)
8+ *
9+ * ์๊ฐ ๋ณต์ก๋: O(N^(T/M)) - N: ํ๋ณด ๊ฐ์, T: ํ๊ฒ, M: ์ต์๊ฐ
10+ * ๊ณต๊ฐ ๋ณต์ก๋: O(T/M) - ์ฌ๊ท ๊น์ด
11+ */
12+
13+ const combinationSum = ( candidates , target ) => {
14+ const result = [ ] ;
15+
16+ const dfs = ( remain , start , path ) => {
17+ // Base case: ํ๊ฒ ๋ฌ์ฑ
18+ if ( remain === 0 ) {
19+ result . push ( [ ...path ] ) ; // ํ์ฌ ๊ฒฝ๋ก ์ ์ฅ
20+ return ;
21+ }
22+
23+ // Base case: ํ๊ฒ ์ด๊ณผ (pruning)
24+ if ( remain < 0 ) return ;
25+
26+ // ๋ชจ๋ ํ๋ณด ํ์
27+ for ( let i = start ; i < candidates . length ; i ++ ) {
28+ // ๊ฐ์ง์น๊ธฐ: ๋จ์ ๊ฐ๋ณด๋ค ํฌ๋ฉด ์คํต
29+ if ( candidates [ i ] > remain ) continue ;
30+
31+ // ์ ํ
32+ path . push ( candidates [ i ] ) ;
33+
34+ // ํ์ (i๋ถํฐ ์์ - ๊ฐ์ ์ซ์ ์ฌ์ฌ์ฉ ๊ฐ๋ฅ)
35+ dfs ( remain - candidates [ i ] , i , path ) ;
36+
37+ // ๋๋๋ฆฌ๊ธฐ (๋ฐฑํธ๋ํน)
38+ path . pop ( ) ;
39+ }
40+ } ;
41+
42+ dfs ( target , 0 , [ ] ) ;
43+ return result ;
44+ } ;
You canโt perform that action at this time.
0 commit comments