Swift solution - Backtracking


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

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.