Skip to content

Commit 07ec592

Browse files
committed
Solution Combination - Sum
1 parent 021dfb2 commit 07ec592

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

combination-sum/HISEHOONAN.swift

+33
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
//
2+
// Untitled.swift
3+
// Algorithm
4+
//
5+
// Created by 안세훈 on 4/14/25.
6+
//
7+
8+
class Solution {
9+
func combinationSum(_ candidates: [Int], _ target: Int) -> [[Int]] {
10+
var middleArray : [Int] = [] // 연산중인 배열
11+
var resultArray : [[Int]] = [] // 결과 배열
12+
13+
func recursive(startIndex : Int, Sum : Int){ //재귀함수. 시작index, 합계
14+
if Sum == target{ //합계가 목표와 같다면
15+
resultArray.append(middleArray) //결과 배열로 연산배열 append
16+
return //종료
17+
}
18+
if Sum > target{ // 합계가 목표보다 크다면,
19+
return //그대로 리턴
20+
}
21+
//핵심
22+
for i in startIndex..<candidates.count{ // 인덱스 별로 for loop
23+
middleArray.append(candidates[i]) //연산중인 배열에 startIndex의 원소 추가
24+
recursive(startIndex: i, Sum: Sum+candidates[i]) //재귀실행. i번째 인덱스와, i번째 인덱스의 원소 + 지금까지의 합을 더해서 재귀 함수로 리턴.
25+
middleArray.removeLast() // 백트래킹을 위해 맨 뒤 원소 삭제.
26+
}
27+
}
28+
29+
recursive(startIndex: 0, Sum: 0) // 최초 재귀함수 호출. 초기화를 위해 0번째 인덱스와 합계 0부터 시작
30+
print(resultArray) // 디버깅을 위한 출력문
31+
return resultArray // 리턴은 결과 배열
32+
}
33+
}

0 commit comments

Comments
 (0)