LeetCode刷题之119.杨辉三角 II
我不知道将去向何方,但我已在路上! |
时光匆匆,虽未曾谋面,却相遇于斯,实在是莫大的缘分,感谢您的到访 ! |
- 题目:
给定一个非负索引 k,其中 k ≤ 33,返回杨辉三角的第 k 行。在杨辉三角中,每个数是它左上方和右上方的数的和。
- 示例:
输入: 3
输出: [1,3,3,1]
- 进阶:你可以优化你的算法到 O(k) 空间复杂度吗?
- 代码:
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)
- 算法说明:
如果rowIndex小于等于1,表示输出第0行或者第1行,返回对应个数的1即可;当rowIndex大于1时,两层for循环进行求解,第一层for循环,遍历层数i,第二层for循环,按照杨辉三角的规律,求出当前层的元素,并更新暂时列表a_temp,以便进行下一层的求解,返回结果a。