Swift 3 Iterative Method by Level


  • 1
    Y
    func pathSum(_ nums: [Int]) -> Int {
        var hash = [Int: Int]()
        for i in stride(from: nums.count - 1, through: 0, by: -1) {
            let level = nums[i] / 100, pos = nums[i] / 10 % 10
            let index = Int(pow(2.0, Double(level) - 1.0)) - 1 + pos
            // leaf node
            if hash[index] == nil {
                hash[index] = 1
            }
            // child node's parent node
            if hash[index / 2] == nil {
                hash[index / 2] = 0
            }
            // adding child notes' number of child notes together
            hash[index / 2] = hash[index / 2]! + hash[index]!
        }
        var sum = 0
        for i in 0..<nums.count {
            let level = nums[i] / 100, pos = nums[i] / 10 % 10, val = nums[i] % 10
            // calculate
            let index = Int(pow(2.0, Double(level) - 1.0)) - 1 + pos
            sum += hash[index]! * val
        }
        return sum
    }
    
    

Log in to reply
 

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