Pascal's Triangle
Total Accepted: 13674 Total Submissions: 43141 My Submissions
Given numRows, generate the first numRows of Pascal's triangle.
For example, given numRows = 5,
Return
1、numRows表示有几行,注意列表从0开始。
2、每一行的列表是这样构成的,开头和结尾都是1,中间是前一个列表相邻两个数之和。
Total Accepted: 13674 Total Submissions: 43141 My Submissions
Given numRows, generate the first numRows of Pascal's triangle.
For example, given numRows = 5,
Return
[ [1], [1,1], [1,2,1], [1,3,3,1], [1,4,6,4,1] ]【解题思路】
1、numRows表示有几行,注意列表从0开始。
2、每一行的列表是这样构成的,开头和结尾都是1,中间是前一个列表相邻两个数之和。
Java AC 364ms
public class Solution {
public ArrayList<ArrayList<Integer>> generate(int numRows) {
ArrayList<ArrayList<Integer>> list = new ArrayList<ArrayList<Integer>>();
if(numRows <= 0){
return list;
}
ArrayList<Integer> firstList = new ArrayList<Integer>();
firstList.add(1);
list.add(firstList);
for(int i = 1; i < numRows; i++){
ArrayList<Integer> secList = new ArrayList<Integer>();
ArrayList<Integer> tempList = list.get(i-1);
int size = tempList.size();
secList.add(1);
for(int j = 1; j < size; j++){
secList.add(tempList.get(j-1) + tempList.get(j));
}
secList.add(1);
list.add(secList);
}
return list;
}
}
Python AC 120ms
class Solution:
# @return a list of lists of integers
def generate(self, numRows):
list = []
if numRows <= 0:
return []
list.append([1])
for i in range(1, numRows):
tempList = list[i-1]
rowList = []
rowList.append(1)
for j in range(1,len(tempList)):
rowList.append(tempList[j-1] + tempList[j])
rowList.append(1)
list.append(rowList)
return list