113. 路径总和 II

2022-08-02  本文已影响0人  邦_


func pathSum(_ root: TreeNode?, _ targetSum: Int) -> [[Int]] {
        if root == nil {
            return []
        }
        var tempArray = Array<Int>()
        var ans = Array<Array<Int>>()
        var sum = root!.val
        tempArray.append(sum)
        dfs(0,root,&tempArray,targetSum,&sum,&ans)
        return ans

    }
        
    func dfs(_ index:Int,_ tempNode:TreeNode?,_ tempArray: inout [Int],_ targetSum:Int,_ sum:inout Int,_ ans:inout [[Int]]){
            
            if tempNode?.left == nil && tempNode?.right == nil {
                //说明找到了
                if sum == targetSum {
                    ans.append(tempArray)
                }
                return
                
            }
            var array = Array<TreeNode?>()
            if tempNode?.left != nil {
                array.append(tempNode?.left)
            }
            if tempNode?.right != nil {
                 array.append(tempNode?.right)
            }
            for node in array {
                
                tempArray.append(node!.val)
                sum += node!.val
                dfs(index + 1,node,&tempArray,targetSum,&sum,&ans)
                sum -= tempArray.removeLast()
            }
                        
                
        }







上一篇 下一篇

猜你喜欢

热点阅读