File tree 1 file changed +49
-0
lines changed
1 file changed +49
-0
lines changed Original file line number Diff line number Diff line change
1
+ /**
2
+ * NOTE:
3
+ * 1. dp를 사용하려고 했으나 시간초과
4
+ * 2. 재귀를 활용해 가능한 한 모든 중복조합을 구해서 계산하기
5
+ *
6
+ */
7
+
8
+ // 1번 시도
9
+
10
+ var combinationSum = function ( candidates , target ) {
11
+ const dp = Array ( target + 1 ) . fill ( 1 ) ;
12
+
13
+ for ( let i = 2 ; i < candidates . length ; i ++ ) {
14
+ dp [ i ] = 1 ;
15
+ for ( let j = 1 < Math . floor ( i / 2 ) ; ; j ++ ) {
16
+ dp [ i ] += dp [ j ] * dp [ i - j ] ;
17
+ }
18
+ // ...이미 시간초과
19
+ }
20
+ } ;
21
+
22
+ // 2번 풀이(참고)
23
+ // 재귀를 활용해 한 값이 중복으로 더해지는 부분을 처리 -> target보다 클때까지 재귀
24
+ // for 문을 활용해 candidates의 모든 값을 순회
25
+ //
26
+ /**
27
+ * Runtime: 78ms, Memory: 59.13MB
28
+ * Time complexity: O(n * target/n) => O(2^n * k) by gpt (k: 조합의 길이)
29
+ * Space complexity: O(n * target/n) => O(target) + O(2^n * k ) by gpt
30
+ *
31
+ */
32
+
33
+ var combinationSum = function ( candidates , target ) {
34
+ const result = [ ] ;
35
+
36
+ function permute ( arr = [ ] , sum = 0 , idx = 0 ) {
37
+ // target보다 합이 크면 리턴
38
+ if ( sum > target ) return ;
39
+ // 같은 경우에만 result에 담기
40
+ if ( sum === target ) result . push ( arr ) ;
41
+
42
+ for ( let i = idx ; i < candidates . length ; i ++ ) {
43
+ // target보다 합이 작으면 재귀적으로 해당 값을 arr에 넣고, sum에 추가
44
+ permute ( [ ...arr , candidates [ i ] ] , sum + candidates [ i ] , i ) ;
45
+ }
46
+ }
47
+ permute ( ) ;
48
+ return result ;
49
+ } ;
You can’t perform that action at this time.
0 commit comments