[题解][LeetCode][Pascal's Triangle II]
2014-07-28 22:57
507 查看
题目:
Given an index k, return the kth row of the Pascal's triangle.
For example, given k = 3,
Return
Note:
Could you optimize your algorithm to use only O(k) extra space?
题解:
杨辉三角形
1
1 1
1 2 1
1 3 3 1
....
发现
1. 第一个位置为1
2. 新增的数字为1
3. 其他位置的值为当前值加上它前面的那个值
注意,O(k)空间情况下,要从后向前遍历,这样才能保证你加你前面那个数字的时候,那个数字还是旧一行的。如果从前向后的话,你处理后面的值的时候,这个值前面的数字已经更新为新的值了,就错了。
Code:
class Solution:
# @return a list of integers
def getRow(self, rowIndex):
a = [1]
k = 0;
while rowIndex > k:
k+=1
for i in range(1,k)[::-1]:
a[i] = a[i]+a[i-1]
a.append(1)
return a
Given an index k, return the kth row of the Pascal's triangle.
For example, given k = 3,
Return
[1,3,3,1].
Note:
Could you optimize your algorithm to use only O(k) extra space?
题解:
杨辉三角形
1
1 1
1 2 1
1 3 3 1
....
发现
1. 第一个位置为1
2. 新增的数字为1
3. 其他位置的值为当前值加上它前面的那个值
注意,O(k)空间情况下,要从后向前遍历,这样才能保证你加你前面那个数字的时候,那个数字还是旧一行的。如果从前向后的话,你处理后面的值的时候,这个值前面的数字已经更新为新的值了,就错了。
Code:
class Solution:
# @return a list of integers
def getRow(self, rowIndex):
a = [1]
k = 0;
while rowIndex > k:
k+=1
for i in range(1,k)[::-1]:
a[i] = a[i]+a[i-1]
a.append(1)
return a
相关文章推荐
- Leetcode题解 119. Pascal's Triangle II
- leetcode题解-118. Pascal's Triangle && 119. Pascal's Triangle II
- LeetCode题解:Pascal's Triangle II
- LeetCode 119: Pascal's Triangle II
- 【LeetCode】119 Pascal's Triangle II
- leetcode之Pascal's Triangle I 和 II 解题思路
- leetcode -- Pascal's Triangle II -- 简单
- [leetcode, python] Pascal's Triangle II 杨辉三角
- LeetCode笔记:119. Pascal's Triangle II
- Leetcode 119. Pascal's Triangle II
- leetcode:Pascal's Triangle II (杨辉三角形,空间限制)【面试算法题】
- ※ Leetcode - Dynamic Programming - 119. Pascal's Triangle II(倒叙滚动数组求解杨辉三角第k行)
- [leetCode]119.Pascal's Triangle II
- LeetCode - Pascal's Triangle II
- LeetCode WIith JS || 119. Pascal's Triangle II
- leetcode:Pascal's Triangle II 【Java】
- [LeetCode] 119. Pascal's Triangle II
- leetcode: (119) Pascal's Triangle II
- Leetcode 第119题 Pascal's Triangle II
- LeetCode-119. Pascal's Triangle II