File tree Expand file tree Collapse file tree 3 files changed +74
-0
lines changed Expand file tree Collapse file tree 3 files changed +74
-0
lines changed Original file line number Diff line number Diff line change 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+ }
Original file line number Diff line number Diff line change 1+ //
2+ // Untitled.swift
3+ // Algorithm
4+ //
5+ // Created by 안세훈 on 4/14/25.
6+ //
7+
8+ class Solution {
9+ func hammingWeight( _ n: Int ) -> Int {
10+ var num = n //n을 저장할 변수
11+ var remain = 0 //나머지를 저장할 변수
12+ var array : [ Int ] = [ ] //이진법으로 변환한 수를 저장할 배열
13+
14+ while num > 0 { //num이 0보다 클때만 반복
15+ remain = num % 2 //num을 2로 나눈 나머지를 저장
16+ num = num / 2 //num을 2로 나눈 몫을 저장
17+ array. append ( remain) //array에 나머지를 저장
18+ }
19+
20+ return array. filter { $0 == 1 } . count //array에 1만 추출한 후 그 개수 리턴
21+ }
22+ }
Original file line number Diff line number Diff line change 1+ //
2+ // Untitled.swift
3+ // Algorithm
4+ //
5+ // Created by 안세훈 on 4/14/25.
6+ //
7+
8+ class Solution {
9+ func isPalindrome( _ s: String ) -> Bool {
10+ var validS = s. lowercased ( ) . filter { $0. isNumber == true || $0. isLetter == true }
11+ //s를 모두 소문자로 변환 후 숫자 or 문자가 true인 문자만 validS에 배열로 추출.
12+
13+ if validS == String ( validS. reversed ( ) ) { //validS와 뒤집은 것과 같다면 true 아니면 false
14+ return true
15+ } else {
16+ return false
17+ }
18+ }
19+ }
You can’t perform that action at this time.
0 commit comments