1+ /**
2+ * @param {number[] } candidates
3+ * @param {number } target
4+ * @return {number[][] }
5+ */
6+
7+ /**
8+ * candidates๋ฅผ ์ฌ๋ฌ๋ฒ ์ฌ์ฉํด๋ ๋๋ค. ํ์ง๋ง ์ฌ์ฉํ ์ข
๋ฅ์ ๊ฐ์๊ฐ ๋ชจ๋ ๊ฐ์ผ๋ฉด ์๋๋ค.
9+ *
10+ */
11+ var combinationSum = function ( candidates , target ) {
12+ const candidatesLength = candidates . length
13+ // ์์ ์์ ์์ array๋ฅผ ๋ง๋ค์ด์ ๋๊ฒจ์ค์ผํ๋ค.
14+ // candidates ์ค์ ๋ฃ์ผ๋ฉด target์ด ๋๋ฉด ๋ต์ ๊ทธ ๋ฐฐ์ด์ ๋ฃ๊ณ ํ์ถํ๋ค.
15+ // ๋ง์ฝ ๋ํ๋๋ฐ target๋ณด๋ค ํฌ๋ฉด ๊ทธ๋ฅ ๋ฆฌํดํ๋ค.
16+ // target๋ณด๋ค ์์๊ฒ์ ๋ํด์ ๋ฃ๋๋ค.
17+ const ret = [ ]
18+ function dp ( total , newNum , currentArr ) {
19+ if ( total + newNum > target ) {
20+ return
21+ }
22+ if ( total + newNum == target && ) {
23+ ret . push ( [ ...currentArr , newNum ] ) ;
24+ return
25+ }
26+
27+ //๋ ๊ฐ์ง ์ด๋๊ฒ์๋ ํด๋นํ์ง ์์ผ๋ฉด ์ฌ๊ท๋ฅผ ๋ ๋ค์ ๋๋ค.
28+ for ( let i = 0 ; i < candidatesLength ; i ++ ) {
29+ dp ( total + newNum , candidates [ i ] , [ ...currentArr , candidates [ i ] ] )
30+ }
31+ }
32+ dp ( 0 , 0 , [ ] )
33+ return ret
34+ } ;
35+
36+ //์ฌ๊ธฐ์ ๋ฌธ์ ๊ฐ ์๊ฒผ๋ค.
37+ // ์ค๋ณต์ด ์๊ธด๋ค๋ ๊ฒ์ด๋ค. ์ด๋ป๊ฒ ์ค๋ณต์ ์ ๊ฑฐํ๋ฉด ์ข์๊น?
38+ /**
39+ * 1. Set์ ์ด์ฉํ๋ค.
40+ * 2. ์์๋ฅผ ๋๋ค. idx๋ฅผ dfs์ ๋๊ฒจ์ฃผ์ด์, ์์๋๋ก ์๋ํ๊ฒ ํ๋ค.
41+ */
42+
43+ var combinationSum = function ( candidates , target ) {
44+ const candidatesLength = candidates . length
45+ const ret = [ ]
46+ function dp ( idx , total , currentArr ) {
47+ if ( total > target ) {
48+ return
49+ }
50+ if ( total == target ) {
51+ ret . push ( currentArr ) ;
52+ return
53+ }
54+
55+ //idx๋ฅผ ๋๊ฒจ๋ฐ์์, ๊ทธ ์ดํ์ ๊ฒ์๋ง(์๊ธฐ ์์ ํฌํจ) ๋๊ฒ ๋๋ค. ๊ทธ๋ฌ๋ฉด ์ ๋ฐ์ ๋๋ง ๋๋ค๊ณ ๋ณผ ์ ์๋ค.
56+ for ( let i = idx ; i < candidatesLength ; i ++ ) {
57+ dp ( i , total + candidates [ i ] , [ ...currentArr , candidates [ i ] ] )
58+ }
59+ }
60+ dp ( 0 , 0 , [ ] )
61+ return ret
62+ } ;
63+
64+
65+
66+ /**
67+ ์๊ฐ๋ณต์ก๋: O(N^(target/min)) : N๊ฐ ํ๋ณด ์ค ์ ํํ๋ ๊ฒฝ์ฐ์ ์๊ฐ target/min ๊น์ด๋งํผ ๋ฐ๋ณต
68+ ๊ณต๊ฐ๋ณต์ก๋: O(target/min) : ์ฌ๊ท ์คํ์ ์ต๋ ๊น์ด๊ฐ target/min
69+
70+
71+ */
72+
73+
74+ // 2. dp๋ฅผ ํ์ฉํ ๋ฌธ์ ํด๊ฒฐ๋ฐฉ๋ฒ
75+ var combinationSum = function ( candidates , target ) {
76+ const dp = Array . from ( { length :target + 1 } , ( ) => [ ] )
77+ dp [ 0 ] = [ [ ] ] ;
78+ for ( let candidate of candidates ) {
79+ //์ฌ๊ธฐ์ candidate์ ๋ํด์, ์ดํ ํ๊ฒ๊น์ง ๋ํ ์์๋ ์ซ์์ ๋ํ ์กฐํฉ์, candidate๋ฅผ ๊ฐ๊ฐ ๋ฃ์ด์ค๋ค.
80+ for ( let i = candidate ; i <= target ; i ++ ) {
81+ for ( let comb of dp [ i - candidate ] ) { //๊ฐ ์กฐํฉ์ ๋ฃ์ด์ค
82+ dp [ i ] . push ( [ ...comb , candidate ] )
83+ }
84+ }
85+ }
86+ return dp [ target ]
87+ } ;
88+ /**
89+ ์๊ฐ๋ณต์ก๋: O(N ร target ร 2^target)
90+ N๊ฐ ํ๋ณด๋ฅผ ์ํํ๋ฉด์, ๊ฐ ํ๋ณด๋ง๋ค target๊น์ง์ ๊ฐ๋ค์ ๋ํด ๊ธฐ์กด ์กฐํฉ๋ค์ ๋ณต์ฌํด์ ์ ์กฐํฉ์ ์์ฑํ๋๋ฐ, ์กฐํฉ ๊ฐ์๊ฐ ์ง์์ ์ผ๋ก ์ฆ๊ฐํจ
91+ ๊ณต๊ฐ๋ณต์ก๋: O(target ร 2^target)
92+ dp ๋ฐฐ์ด์ ๊ฐ ์ธ๋ฑ์ค์ ํด๋น ๊ฐ์ ๋ง๋๋ ๋ชจ๋ ์กฐํฉ๋ค์ ์ ์ฅํ๋ฉฐ, ์ต์
์ ๊ฒฝ์ฐ ์กฐํฉ ๊ฐ์๊ฐ ์ง์์ ์ผ๋ก ์ฆ๊ฐํจ
93+ */
0 commit comments