File tree 3 files changed +58
-0
lines changed
3 files changed +58
-0
lines changed Original file line number Diff line number Diff line change
1
+ // 해설 참조..
2
+ class Solution {
3
+ func combinationSum( _ candidates: [ Int ] , _ target: Int ) -> [ [ Int ] ] {
4
+ // 우선 답변용, 조합 찾기용 변수 생성
5
+ var answer = [ [ Int] ] ( )
6
+ var nums = [ Int] ( )
7
+ // 백트래킹 기법으로 로직 작성,
8
+ // 현재 원소 위치와 합했을때의 값을 인자로 받음
9
+ func backtracking( start: Int , total: Int ) {
10
+ // 전처리
11
+ if total > target { return } // total이 target 보다 크면 조합X
12
+ else if total == target { return answer. append ( nums) } // 같으면 답변용 변수에 추가
13
+
14
+ // 시작 부분부터 값을 하나씩 더해서 재귀로 돌려봄
15
+ for index in start..< candidates. count {
16
+ let temp = candidates [ index]
17
+ nums. append ( temp) //먼저 선택된 원소를 조합 배열에 추가
18
+ backtracking ( start: index, total: total + temp) // 현재 선택된 원소의 인덱스와 총 합을 인자로 함수 호출
19
+ nums. removeLast ( ) // 조합찾기가 끝나면 종료
20
+ }
21
+ }
22
+ // 초기부터 시작함
23
+ backtracking ( start: 0 , total: 0 )
24
+ return answer
25
+ }
26
+ }
Original file line number Diff line number Diff line change
1
+ // time: O(n)
2
+ class Solution {
3
+ func hammingWeight( _ n: Int ) -> Int {
4
+ return String ( n, radix: 2 ) . filter { $0 == " 1 " } . count
5
+ }
6
+ }
7
+ // time: O(1), space: O(1)
8
+ class AnotherSolution {
9
+ func hammingWeight( _ n: Int ) -> Int {
10
+ var count = 0
11
+ var num = n
12
+ // 최대 32비트이기 때문에 반복을 32번 돌며 비트를 순회함
13
+ for _ in 0 ..< 32 {
14
+ if num & 1 == 1 { // 가장 오른쪽 비트만 가져와 1인지 확인함
15
+ count += 1 // 비트가 1이면 count 증가
16
+ }
17
+ num >>= 1 // 오른쪽으로 1비트 이동
18
+ }
19
+ return count
20
+ }
21
+ }
Original file line number Diff line number Diff line change
1
+ class Solution {
2
+ func isPalindrome( _ s: String ) -> Bool {
3
+ let answer = s. lowercased ( ) . filter {
4
+ if $0. isLetter || $0. isNumber {
5
+ return true
6
+ }
7
+ return false
8
+ }
9
+ return answer == String ( answer. reversed ( ) ) ? true : false
10
+ }
11
+ }
You can’t perform that action at this time.
0 commit comments