Leetcode-pascals-triangle-ii

来源:互联网 发布:aws ec2 centos 编辑:程序博客网 时间:2024/06/05 04:55

题目描述


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?

一开始不懂Pascal's triangle,后来一查就是杨辉三角形。

         1

      1     1

   1    2     1

 1   3     3    1

题目中是以ArrayList存储最终结果的,要返回的也是ArrayList。

需要注意的是,根据i-1行的结果计算i行的数据的时候,list从后往前计算,如果从前往后,则无法获取到原有数据,因为被覆盖了!

import java.util.*;public class Solution {    public ArrayList<Integer> getRow(int rowIndex) {        ArrayList<Integer> list = new ArrayList<Integer>();    if(rowIndex < 0 )    return list;    list.add(1);    for(int i=1; i<=rowIndex; i++){    for(int j=list.size()-2; j>=0; j--){    list.set(j+1, list.get(j)+list.get(j+1));    }    list.add(1);    }    return list;    }}
其实很简单,rowIndex为几那一行就有j+1个数。其中第一个和最后一个是1,其他数则是上一行数两两相加的结果。

代码中非常清晰!

0 0
原创粉丝点击