2014
11-19

# LeetCode-Pascal’s Triangle[模拟]

### Pascal’s Triangle

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]
]


// LeetCode, Pascal's Triangle
// 时间复杂度O(n^2)，空间复杂度O(n)
class Solution {
public:
vector<vector<int> > generate(int numRows) {
vector<vector<int> > result;
if(numRows == 0) return result;

result.push_back(vector<int>(1,1)); //first row

for(int i = 2; i <= numRows; ++i) {
vector<int> current(i,1);  // 本行
const vector<int> &prev = result[i-2];  // 上一行

for(int j = 1; j < i - 1; ++j) {
current[j] = prev[j-1] + prev[j]; // 左上角和右上角之和
}
result.push_back(current);
}
return result;
}
};


// LeetCode, Pascal's Triangle
// 时间复杂度O(n^2)，空间复杂度O(n)
class Solution {
public:
vector<vector<int> > generate(int numRows) {
vector<vector<int> > result;
vector<int> array;
for (int i = 1; i <= numRows; i++) {
for (int j = i - 2; j > 0; j--) {
array[j] = array[j - 1] + array[j];
}
array.push_back(1);
result.push_back(array);
}
return result;
}
};


Java代码:

class Solution:
# @return a list of lists of integers
def generate(self, numRows):
arr = [[1]]
if numRows < 1: return []
#if numRows == 1: return arr
for i in range(2,numRows+1):
row = [1]*i
for j in range(1,i-1):
row[j] = arr[i-2][j-1] + arr[i-2][j]
arr.append(row)
return arr

1. 代码不对，仔细对比一下输入输出， 怎么会有‘‘printf("The winning moves are:");’’这种输出呢？