백준 10974번을 스위프트로 풀면서 난관에 봉착했습니다.
파이썬에는 간단한 순열 & 조합이 스위프트엔 없다는 것이죠.
스위프트를 공부한 지 얼마 되지 않은 상황에서,
파이썬에선 기본함수인 걸 직접 구현해야 한다는 말은 꽤 충격으로 다가왔습니다.
많은 글을 찾아보고 참고하여,
순열 혹은 조합 문제가 주어졌을 때 제일 유용할만한 코드를 구현했습니다.
순열
Permutation
// 구현해놓은 Permutation 연습
func permute(_ nums: [Int], _ targetNum: Int) -> [[Int]] {
var result = [[Int]]()
var visited = [Bool](repeating: false, count: nums.count)
func permutation(_ nowPermute: [Int]) {
if nowPermute.count == targetNum {
result.append(nowPermute)
return
}
for i in 0..<nums.count {
if visited[i] == true {
continue
}
else {
visited[i] = true
permutation(nowPermute + [nums[i]])
visited[i] = false
}
}
}
permutation([])
return result
}
참고한 글 : https://icksw.tistory.com/180 | https://youseokhwan.me/blog/permutation-combination/ | t.ly/GtSn
조합
Combination
Ver 1
// 조합 연습(Ver 1)
func combi(_ nums: [Int], _ targetNum: Int) -> [[Int]] {
var result = [[Int]]()
var visited = Array(repeating: false, count: nums.count)
func combination(_ index: Int, _ nowCombi: [Int]) {
if nowCombi.count == targetNum {
result.append(nowCombi)
return
}
for i in index..<nums.count {
if visited[i] == true {
continue
}
else {
visited[i] = true
combination(i+1, nowCombi + [nums[i]])
visited[i] = false
}
}
}
combination(0, [])
return result
}
print(combi([3, 5, 10, 9, 22], 3))
Ver 2
// 구현해놓은 Combination 연습(Ver 2)
func combi(_ nums: [Int], _ targetNum: Int) -> [[Int]] {
var result = [[Int]]()
func combination(_ index: Int, _ nowCombi: [Int]) {
if nowCombi.count == targetNum {
result.append(nowCombi)
return
}
for i in index..<nums.count {
combination(i + 1, nowCombi + [nums[i]])
}
}
combination(0, [])
return result
}
참고한 글 : https://ssooyn.tistory.com/24 | t.ly/sW3F
코드 중 이해가 안 되는 부분이 있거나, 잘못된 부분이 있다면 편하게 댓글 부탁드립니다.
https://developer-p.tistory.com/146
스위프트 | "스택과 큐 구현"하기 (Swift5 | Stack, Queue)
백준 1935번을 풀다가, 스위프트엔 스택 & 큐가 없다는 사실을 알게 되었습니다. 지난번 게시글과 똑같은 상황이죠? 네. 구현해야 합니다... (스택은 아닐지도~ 아래에서 설명합니다.) https://developer
developer-p.tistory.com
https://developer-p.tistory.com/190
스위프트 | "(최소)힙 구현"하기 (Swift5 | Heap - MinHeap)
코테알고리즘 공부를 하던 중, 백준 1927번을 풀기 위해선 최소힙(MinHeap) 구현이 필요했습니다. Swift엔 힙이 없습니다. 물론 큐, 덱, 순열, 조합 등등 다 없습니다... https://developer-p.tistory.com/146 스..
developer-p.tistory.com
최근댓글