【Leetcode】Pascal's Triangle II

来源:互联网 发布:michael angelo 知乎 编辑:程序博客网 时间:2024/06/03 15:16

题目链接:https://leetcode.com/problems/pascals-triangle-ii/

题目:

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?

思路:

要求空间复杂度为O(k),其实只需要记录前一行的结果就可以了。

算法:

[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. public List<Integer> getRow(int rowIndex) {  
  2.         List<Integer> pre;  
  3.         List<Integer> cur=null;  
  4.         for (int i = 1; i <= rowIndex + 1; i++) {  
  5.             pre = cur;  
  6.             cur = new ArrayList<Integer>();  
  7.             if (i == 1) {  
  8.                 cur.add(1);  
  9.             } else if (i == 2) {  
  10.                 cur.add(1);  
  11.                 cur.add(1);  
  12.             } else if (i > 2) {  
  13.                 cur.add(1);  
  14.                 for (int j = 0; j < pre.size() - 1; j++) {  
  15.                     cur.add(pre.get(j) + pre.get(j + 1));  
  16.                 }  
  17.                 cur.add(1);  
  18.             }  
  19.         }  
  20.         return cur;  
  21.     }  
1 0