118. Pascal’s Triangle
https://leetcode.com/problems/pascals-triangle/
Description
Given a non-negative integer numRows, generate the first numRows of Pascal’s triangle.
In Pascal’s triangle, each number is the sum of the two numbers directly above it.
Example:
Input: 5
Output:
[
[1],
[1,1],
[1,2,1],
[1,3,3,1],
[1,4,6,4,1]
]
Solutions
杨辉三角:
- 每行的第一列和最后一列均为1;
- 每个数等于它上方两数之和。
步骤:
外层大list res
前一行list front
每一行list ls
- 先直接赋值1得到第一行,作为front list,再逐行生成。
在每行中,首尾add(1),其他元素等于front.get(j-1)+front.get(j)。
Submissions
class Solution {
public List<List<Integer>> generate(int numRows) {
List<List<Integer>> res=new ArrayList<>();
List<Integer> front=new ArrayList<>();
if(numRows>0)
{
front.add(1);
res.add(front);
}
for(int i=1;i<numRows;i++)
{
List<Integer> ls=new ArrayList<>();
ls.add(1);
for(int j=1;j<i;j++)
{
ls.add(front.get(j-1)+front.get(j));
}
ls.add(1);
res.add(ls);
front=ls;
}
return res;
}
}
Summary
一开始,我把每层的ls是定义在for循环外。而在for循环里,每次生成完一行之后都要clear,clear之前做赋值front=ls;
,但是我发现,clear之后front也指向null了。这里要注意对象赋值不是赋值本身,而是指向同一个对象。如果一个被修改或删除,另一个也会被修改或删除。