[LeetCode][Java] Pascal's Triangle II

来源:互联网 发布:nginx 域名跳转tomcat 编辑:程序博客网 时间:2024/05/29 02:12

题目:

Given an index k, return the kth row of the Pascal's triangle.

For example, given k = 3,
Return [1,3,3,1].

题意:

给定序号 k,返回杨辉三角中的第k行。

比如,给定k = 3,

返回[1,3,3,1].

算法分析:

与题目《Pascal's Triangle》算法类似,每个元素等于上一行的对应两元素的和值,这里只是不把每一行都保存,只需推导到所求行即可。

AC代码:

<span style="font-family:Microsoft YaHei;font-size:12px;">public class Solution{public static List<Integer> getRow(int rowIndex)     {        List<Integer> a=new ArrayList<Integer>();               for (int i=0;i<=rowIndex;i++)        {        Integer[] ta =new Integer[a.size()];            a.toArray(ta);        for(int j=0;j<i+1;j++)            {                if(j==i) a.add(j,1);                else if (j==0) a.set(j,1);                else                {                   int temp=ta[j-1]+ta[j];                   a.set(j,temp);                 }            }        }        return a;    }}</span>

0 0
原创粉丝点击