Total Accepted: 19384 Total Submissions: 63446 My Submissions Question Solution
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),与上一题 杨辉三角 类似,但是我们稍微改一下,只需要存上一行的结果就行了。
这样就不需要消耗太多内存。

更厉害的是:Inplace也可以,只要你每次从后往前扫描就行了。一个array也能搞定:

 1 public class Solution {
 2     public List<Integer> getRow(int rowIndex) {
 3         List<Integer> ret = new ArrayList<Integer>();
 4         
 5         for (int i = 0; i <= rowIndex; i++) {
 6             for (int j = i; j >= 0; j--) {
 7                 if (j == i) {
 8                     ret.add(1);
 9                 } else if (j != 0) {
10                     // ERROR: use add instead of set
11                     //ret.add(ret.get(j) + ret.get(j - 1));
12                     ret.set(j, ret.get(j) + ret.get(j - 1));
13                 }
14             } 
15         }
16         
17         return ret;
18     }
19 }
View Code

相关文章:

  • 2021-10-07
  • 2022-12-23
  • 2021-12-19
  • 2021-10-08
  • 2022-01-12
  • 2022-12-23
  • 2021-09-23
猜你喜欢
  • 2022-01-07
  • 2022-12-23
  • 2022-12-23
  • 2022-01-27
  • 2022-02-23
  • 2022-02-26
  • 2021-08-12
相关资源
相似解决方案