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]
]
楊輝三角形,又稱賈憲三角形、帕斯卡三角形、海亞姆三角形、巴斯卡三角形,是二項式系數在的一種寫法,形似三角形,在中國首現於南宋楊輝的《詳解九章算術》得名,書中楊輝說明是引自賈憲的《釋鎖算術》,故又名賈憲三角形。前 9 行寫出來如下:
1 1 1 1 2 1 1 3 3 1 1 4 6 4 1 1 5 10 10 5 1 1 6 15 20 15 6 1 1 7 21 35 35 21 7 1 1 8 28 56 70 56 28 8 1
楊輝三角形第
層(頂層稱第 0 層,第 1 行,第
層即第
行,此處
為包含 0 在內的自然數)正好對應於二項式
展開的系數。例如第二層 1 2 1 是冪指數為 2 的二項式
展開形式
的系數。
解法:每一行的首個和結尾一個數字都是1,從第三行開始,中間的每個數字都是上一行的左右兩個數字之和。
Java:
public class Solution {
public List<List<Integer>> generate(int numRows) {
List<List<Integer>> res = new ArrayList<>();
if (numRows <= 0) return res;
List<Integer> list = new ArrayList<>();
for (int i = 1; i <= numRows; i++) {
list.add(1);
for (int j = list.size() - 2; j > 0; j--) {
list.set(j, list.get(j) + list.get(j - 1));
}
res.add(new ArrayList<>(list));
}
return res;
}
}
Java:
public class Solution {
public List<List<Integer>> generate(int numRows) {
List<List<Integer>> res = new ArrayList<>();
if(numRows <= 0)
return res;
ArrayList<Integer> list = new ArrayList<>();
list.add(1);
res.add(list);
for(int i = 1; i < numRows; i++) {
ArrayList<Integer> temp = new ArrayList<>();
temp.add(1);
for(int j = 1; j < res.get(i - 1).size(); j++)
temp.add(res.get(i - 1).get(j) + res.get(i - 1).get(j - 1));
temp.add(1);
res.add(temp);
}
return res;
}
}
Python:
class Solution:
# @return a list of lists of integers
def generate(self, numRows):
result = []
for i in xrange(numRows):
result.append([])
for j in xrange(i + 1):
if j in (0, i):
result[i].append(1)
else:
result[i].append(result[i - 1][j - 1] + result[i - 1][j])
return result
Python:
class Solution:
def generate(self, numRows):
if not numRows: return []
res = [[1]]
for i in range(1, numRows):
res += [map(lambda x, y: x + y, res[-1] + [0], [0] + res[-1])]
return res[:numRows]
C++:
class Solution {
public:
vector<vector<int> > generate(int numRows) {
vector<vector<int> > res;
if (numRows <= 0) return res;
res.assign(numRows, vector<int>(1));
for (int i = 0; i < numRows; ++i) {
res[i][0] = 1;
if (i == 0) continue;
for (int j = 1; j < i; ++j) {
res[i].push_back(res[i-1][j] + res[i-1][j-1]);
}
res[i].push_back(1);
}
return res;
}
};
類似題目:
[LeetCode] 119. Pascal's Triangle II 楊輝三角 II
All LeetCode Questions List 題目匯總
