Swift solution - Backtracking


  • 0
    class Solution {
        func grayCode(_ n: Int) -> [Int] {
            var result = [Int]()
            var val = 0
            
            backtracking(n, n - 1, &val, &result)
            
            return result
        }
        
        private func backtracking(_ n: Int, _ index: Int, _ val: inout Int, _ result: inout [Int]) {
            if index == -1 {
                result.append(val)
                return
            }
            
            backtracking(n, index - 1, &val, &result)
            val ^= (1 << index)
            backtracking(n, index - 1, &val, &result)
        }
    }
    

Log in to reply
 

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