Description
Given a non-negative index k where k ≤ 33, return the kth index row of the Pascal’s triangle.
Note that the row index starts from 0.
In Pascal’s triangle, each number is the sum of the two numbers directly above it.
Example:
1 | Input: 3 |
Follow up:
Could you optimize your algorithm to use only O(k) extra space?
解法
118题的变体,这里我先用递归写了一遍:
具体代码如下:
1 | class Solution { |
在网上看到有更妙的解法:
1 | public List<Integer> getRow(int rowIndex) { |
在0的位置添上1:[1],此时为第一行,不满足则继续;
不执行小循环,继续0的位置添上1:[1,1],此时为第二行,不满足则继续;
不执行小循环,继续0的位置添上1:[1,1,1],执行小循环,得[1,2,1],此时为第三行,不满足则继续;
此时继续0的位置添上1:[1,1,2,1],执行小循环,得[1,3,3,1],此时为第四行,不满足则继续;
……
这样下去确实可以得到每一行的数据,其实就是在一个List内模拟杨辉三角的性质,确实很赞。
原文链接:https://blog.csdn.net/Cloudox_/article/details/52993117