알고리즘
[Swift] 순열 조합
고고
2022. 2. 3. 15:03
실제로 쓸 때에는 T를 특정 자료구조로 바꿔 사용하면 됩니다!
import Foundation
func permute<T>(_ target: [T], _ targetNum: Int) -> [[T]] {
var result = [[T]]()
var visited = Array(repeating: false, count: target.count)
func permutation(_ temp: [T]) {
if temp.count == targetNum {
result.append(temp)
return
}
for i in 0..<target.count {
if visited[i] {
continue
} else {
visited[i] = true
permutation(temp + [target[i]])
visited[i] = false
}
}
}
permutation([])
return result
}
func combi<T>(_ target: [T], _ targetNum: Int) -> [[T]] {
var result = [[T]]()
func combination(_ index: Int, _ temp: [T]) {
if temp.count == targetNum {
result.append(temp)
return
}
for i in index..<target.count {
combination(i + 1, temp + [target[i]])
}
}
combination(0, [])
return result
}
print(permute([1, 2, 3, 4], 2))
print(combi([1, 2, 3, 4], 2))