【leetcode刷题笔记】Pascal's 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?


 

题解:简单的模拟题,每次用answer列表存放上一层的值,用temp列表存放当前层的值,只要计算好temp中需要重新计算的元素的索引范围[1,i-1](第i层),然后根据answer计算就可以了,每次计算完一层更新answer为这一层的数,最后answer中存放的就是答案。

代码如下:

 1 public class Solution {

 2     public List<Integer> getRow(int rowIndex) {

 3         List<Integer> answer = new ArrayList<Integer>();

 4         answer.add(1);

 5         

 6         for(int i = 1;i <= rowIndex;i++){

 7             List<Integer> temp = new ArrayList<Integer>();

 8             temp.add(1);

 9             for(int j = 1;j <= i-1;j++){

10                 temp.add(answer.get(j-1)+answer.get(j));

11             }

12             temp.add(1);

13             answer = temp;

14         }

15         

16         return answer;

17     }

18 }

你可能感兴趣的:(LeetCode)