티스토리 뷰

Coding

Algorithm. permutation 순회

out of coding 2020. 12. 28. 17:03

만약 배열로 무슨 값들이 들어온다고 할 경우에 이것들의 모든 순서의 조합을 만들어야 할 경우가 있습니다.

 

["a", "b", "c"]라는 값이 들어왔을때에

[["a", "b", "c"], ["a", "c", "b"] ... ] 이렇게 값이 나올겁니다.

 

Swift를 이용해서 풀었습니다.

class Permutation<T> {
    func get(_ nums: [T]) -> [[T]] {
        var result = [[T]]()
        var nums = nums
        recurse(0, &nums, &result)
        return result
    }
    
    private func recurse(_ position: Int, _ nums: inout [T], _ result: inout [[T]]) {
        if position == nums.count {
            result.append(nums)
            return
        }
        
        for index in position..<nums.count {
            nums.swapAt(position, index)
            recurse(position + 1, &nums, &result)
            nums.swapAt(position, index)
        }
    }
}

let permutation = Permutation<String>()
let output = permutation.get(["a", "b", "c"])
print(output)

 

'Coding' 카테고리의 다른 글

Swift. Snake -> Camel, Camel -> Snake  (0) 2023.02.18
Python3. lotto 발생기  (0) 2021.04.02
Dynamic Programming  (0) 2020.12.19
Node.js - 구구단  (0) 2020.09.03
Ruby. Gugudan  (0) 2020.08.30
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함