LeetCode刷题之119.杨辉三角 II

LeetCode刷题之119.杨辉三角 II

我不知道将去向何方,但我已在路上!
时光匆匆,虽未曾谋面,却相遇于斯,实在是莫大的缘分,感谢您的到访 !
  • 题目
    给定一个非负索引 k,其中 k ≤ 33,返回杨辉三角的第 k 行。在杨辉三角中,每个数是它左上方和右上方的数的和。
    在这里插入图片描述
  • 示例
输入: 3
输出: [1,3,3,1]
  • 进阶:你可以优化你的算法到 O(k) 空间复杂度吗?
  • 代码:
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
class Solution:
    def hasPathSum(self, root: TreeNode, sum: int) -> bool:
        if root == None:
            return False
        if root.left == None and root.right == None:
            return root.val == sum
        sum = sum-root.val
        return self.hasPathSum(root.left,sum) or self.hasPathSum(root.right,sum)
# 执行用时 :56 ms, 在所有 Python3 提交中击败了92.80%的用户
# 内存消耗 :15.7 MB, 在所有 Python3 提交中击败了5.06%的用户
  • 算法说明:
    如果rowIndex小于等于1,表示输出第0行或者第1行,返回对应个数的1即可;当rowIndex大于1时,两层for循环进行求解,第一层for循环,遍历层数i,第二层for循环,按照杨辉三角的规律,求出当前层的元素,并更新暂时列表a_temp,以便进行下一层的求解,返回结果a。
发布了90 篇原创文章 · 获赞 1 · 访问量 1033

猜你喜欢

转载自blog.csdn.net/qq_34331113/article/details/103861852