목록swift 알고리즘/재귀 (7)
쥐수의 공부노트

정답 : import Foundation let num = Int(readLine()!)! let result = pow(2, num) - 1 func move(from: Int, to : Int) { print("\(from) \(to)") } func hanoi(n : Int, from : Int, by : Int , to : Int) { if n == 1 { move(from: from, to: to) } else { hanoi(n: n-1, from: from, by: to, to: by) move(from: from, to: to) hanoi(n: n-1, from: by, by: from, to: to) } } print(result) hanoi(n: num, from: 1, by: 2, to..

정답 : import Foundation func kanto(n : Double) -> String { if n == 0 { return "-" } let line = kanto(n: n - 1) return line + String(repeating: " ", count: Int(pow(3, n - 1))) + line } while let input = readLine() { let num = Double(input)! let result = kanto(n: num) print(result) } 더보기 TMI : pow의 n - 1은 Double형이여야만 하고, 이 문제에서는 입력이 있을동안은 계속 유지가 되야하는 것 같다..

정답 : let input = readLine()!.split(separator:" ").map{Int(String($0))!} let N = input[0] let K = input[1] var numArray = readLine()!.split(separator:" ").map{Int(String($0))!} var count = 0 var answer = -1 func mergeSort(_ array: [Int], _ start: Int, _ end: Int) { if array.count

풀이 과정 : 팰린드롬을 확인하는 recusion 함수는 문제에서 제공한다. (물론 언어는 Swift가 아니다.) 우리는 recusion 함수에서 조건에 들어가기 전, count를 한개씩 올리면서 함수의 호출 count를 저장한다. 물론 이 count는 return을 할 수 없기에, 입력을 새로 받을때마다 다시 0으로 초기화를 시켜준다. 정답 : func recusion(array : [String], n : Int , m : Int ) -> Int { count += 1 if n >= m { return 1 } else if array[n] != array[m] { return 0 } else { return recusion(array: array, n: n+1, m: m-1) } } let n = I..

풀이 과정 : 피보나치 수열의 특징은 앞의 수와 그 앞의 수를 더한값이다. 기본적으로 피보나치의 수에서 n이 0이면 0, 1이면 1이 된다. 그래서 이 둘을 제약조건으로 걸러준다. fibonacci(n) = fibonacci(n-1) + fibonacci(n-2) 를 이용하여 결과값을 도출하면 된다. 정답 : func fibonacci(num : Int) -> Int { if num