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+ * 주어진 배열의 원소 조합(중복 허용)의 합이 target인 모든 경우를 반환하는 함수
3+ * @param {number[] } candidates
4+ * @param {number } target
5+ * @return {number[][] }
6+ */
7+ const combinationSum = function ( candidates , target ) {
8+ const sortedCandidates = candidates . filter ( ( x ) => x <= target ) . sort ( ( a , b ) => Number ( a ) - Number ( b ) ) ;
9+ const answer = [ ] ;
10+
11+ if ( sortedCandidates . length === 0 ) {
12+ return answer ;
13+ }
14+
15+ function search ( currentIdx , combination , total ) {
16+ if ( total === target ) {
17+ answer . push ( [ ...combination ] ) ; // 배열 자체를 넣으면 참조 때문에 값이 변경되므로, 복사해서 넣어야 함
18+ return ;
19+ }
20+
21+ if ( total > target ) {
22+ return ; // backtracking
23+ }
24+
25+ combination . push ( sortedCandidates [ currentIdx ] ) ;
26+ search ( currentIdx , combination , total + sortedCandidates [ currentIdx ] ) ;
27+ combination . pop ( ) ;
28+
29+ if ( total + sortedCandidates [ currentIdx ] > target ) {
30+ return ; // backtracking
31+ }
32+
33+ if ( currentIdx + 1 < sortedCandidates . length ) {
34+ search ( currentIdx + 1 , combination , total ) ;
35+ }
36+ }
37+
38+ search ( 0 , [ ] , 0 ) ;
39+ return answer ;
40+ } ;
41+
42+ // t: target
43+ // 시간복잡도: O(2^t)
44+ // 공간복잡도: O(t)
You can’t perform that action at this time.
0 commit comments