Swift solution - Backtracking


  • 0
    class Solution {
        func countNumbersWithUniqueDigits(_ n: Int) -> Int {
            let maxNum = Int(NSDecimalNumber(decimal: pow(Decimal(10), n)))
            var count = 1
            var visited = [Bool](repeatElement(false, count: 10))
            
            for i in 1..<10 {
                visited[i] = true
                count += backtracking(i, maxNum, &visited)
                visited[i] = false
            }
            
            return count
        }
        
        private func backtracking(_ num: Int, _ maxNum: Int, _ visited: inout [Bool]) -> Int {
            if num >= maxNum {
                return 0
            }
            
            var count = 1
            
            for i in 0..<10 {
                if !visited[i] {
                    visited[i] = true
                    count += backtracking(10 * num + i, maxNum, &visited)
                    visited[i] = false
                }
            }
            
            return count
        }
    }
    

Log in to reply
 

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