118: Pascal's Triangle Pascal's Triangle
Given a non-negative integer numRows, generate the first numRows of Pascal's triangle.
Given a non-negative integer numRows, generated before Pascal's Triangle of numRows line.
In Pascal's triangle, each number is the sum of the two numbers directly above it.
In Pascal's Triangle, each number is the number of its top left and top right and.
Example:
Input: 5
Output:
[
[1],
[1,1],
[1,2,1],
[1,3,3,1],
[1,4,6,4,1]
]
Problem-solving ideas:
1 is a first row, second row, each of the first and last row is 1, x is assumed that the number of other index position coordinates (m, n), x is the index number is a positive number, and it is above and the number of index just above the left. I.e., (m-1, n), (m-1, n-1) and the number two.
java:
class Solution {
public List<List<Integer>> generate(int numRows) {
List<List<Integer>> triangle = new ArrayList<List<Integer>>();
if(numRows == 0) return triangle;
List<Integer> one = new ArrayList<Integer>();
one.add(1);
triangle.add(one);
if(numRows == 1) return triangle;
for (int i=1;i<numRows;i++){
List<Integer> row = new ArrayList<Integer>();
row.add(1);
for (int j=1;j<i;j++){
List<Integer> prev = triangle.get(i-1);
row.add(prev.get(j-1)+prev.get(j));
}
row.add(1);
triangle.add(row);
}
return triangle;
}
}
python:
class Solution:
def generate(self, numRows: int) -> List[List[int]]:
if numRows==0:return []
triangle=[[1]]
if numRows==1: return triangle
for i in range(1,numRows):
tmp=[1]
for j in range(1,i):
tmp.append(triangle[i-1][j-1]+triangle[i-1][j])
tmp.append(1)
triangle.append(tmp)
return triangle
to sum up:
Very simple a question, you can review the java nested array data structure. Further the inner loop may be added is determined if(i!=0) row.add(1);triangle.add(row);
not equal to 0 plus 1 if i, this may be omitted
List<Integer> one = new ArrayList<Integer>();
one.add(1);
triangle.add(one);
if(numRows == 1) return triangle;
Code segments, but this if(i!=0)
will be determined each time after entering the first cycle. In line with the principle of reducing resource consumption, it should be mentioned outside.