转载自Leet
Code《剑指Offer》
题目描述
给定一个非负索引 rowIndex
,返回「杨辉三角」的第
rowIndex
行。
在「杨辉三角」中,每个数是它左上方和右上方的数的和。
示例 1:
输入: rowIndex
= 3
输出:[1,3,3,1]
示例 2:
输入:rowIndex
=0
输出: [1]
示例 3:
输入: rowIndex = 1
输出: [1,1]
提示:
进阶:
- 你可以优化你的算法到\(O(rowIndex)\)空间复杂度吗?
我的代码
{.line-numbers}1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| class MySolution { public List<Integer> getRow(int rowIndex) { rowIndex++; List<Integer> list = new LinkedList(); if (rowIndex==0) return list; list.add(1); if(rowIndex==1) return list; for(int i=2; i<=rowIndex; i++) { List<Integer> newList = new LinkedList(); newList.add(list.get(0)); for (int j=0, j1=1; j1<list.size(); j++,j1++) newList.add(list.get(j)+list.get(j1)); newList.add(list.get(list.size()-1)); list = new LinkedList(newList); } return list; } }
|