题目:
Given an index k, return the kth row of the Pascal's triangle.
For example, given k = 3,
Return [1,3,3,1]
.
链接: http://leetcode.com/problems/pascals-triangle-ii/
一刷,题目简单,但是需要看清题目,这次是从0行开始的,一开始每行最末尾填0的话可以把从 len(result) - 1到1的下标都一起包括,否则如果填1还要把最后一个去掉
class Solution(object): def getRow(self, rowIndex): if rowIndex < 0: return [] result = [1] for row in range(rowIndex): result.append(0) for idx in range(len(result) - 1, 0, -1): result[idx] = result[idx] + result[idx - 1] return result
1 class Solution(object): 2 def getRow(self, rowIndex): 3 result=[1]*(rowIndex+1) 4 for row in range(2, rowIndex+1): 5 for idx in range(1, row): 6 result[row - idx] += result[row - idx - 1] 7 return result
2/18/2017, Java
多次调试,错误:
1. k=3其实是第4行,看例子得出来的,要注意例子
2. 内循环里,因为如果从前往后赋值会覆盖之前的值,所以内循环从后往前计算。
1 public class Solution { 2 public List<Integer> getRow(int rowIndex) { 3 if (rowIndex < 0) return new ArrayList<Integer>(); 4 5 List<Integer> ret = new ArrayList<Integer>(); 6 for (int i = 0; i <= rowIndex; i++) { 7 ret.add(1); 8 } 9 for (int level = 1; level <= rowIndex; level++) { 10 for (int i = level - 1; i >= 1; i--) { 11 ret.set(i, ret.get(i-1) + ret.get(i)); 12 } 13 } 14 return ret; 15 } 16 }