반응형

Github

 

GitHub - jeongju9216/SwiftAlgorithm: 스위프트 알고리즘

스위프트 알고리즘. Contribute to jeongju9216/SwiftAlgorithm development by creating an account on GitHub.

github.com

 

문제 링크

 

Permutations - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

 

풀이

주어진 input의 모든 순열을 구하는 문제입니다.

 

백트래킹을 이용해 해결하였습니다.

 

1 -> 1, 2 -> 1, 2, 3 -> 리스트 삽입 -> 1, 2 -> 1 -> 1, 3 -> 1, 3, 2 -> 리스트 삽입... 순서로 진행되며

순열을 구할 수 있습니다.

 

전체 코드

더보기

      
class Solution {
var result: [[Int]] = []
func backtracking(_ list: inout [Int], _ nums: [Int]) {
if list.count == nums.count {
result.append(list)
return
}
for num in nums {
if list.contains(num) {
continue
}
list.append(num)
backtracking(&list, nums)
list.removeLast()
}
}
func permute(_ nums: [Int]) -> [[Int]] {
var list: [Int] = []
backtracking(&list, nums)
return result
}
}

아직은 초보 개발자입니다.

더 효율적인 코드 훈수 환영합니다!

공감 댓글 부탁드립니다.

 

Swift, Swift 알고리즘, 스위프트, 알고리즘, LeetCode

반응형
유정주