题目链接
leetcode
题目描述
给定一个非负索引 rowIndex
,返回「杨辉三角」的第 rowIndex
行。
在「杨辉三角」中,每个数是它左上方和右上方的数的和。
C++ 代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
| #include <iostream> #include <vector> using namespace std;
class Solution { public: vector<int> getRow(int rowIndex) { vector<vector<int>> f(rowIndex + 1, vector<int>(rowIndex + 1)); for (int i = 0; i <= rowIndex; i ++) { f[i][0] = f[i][i] = 1; for (int j = 1; j < i; j ++) { f[i][j] = f[i - 1][j - 1] + f[i - 1][j]; } }
return f[rowIndex]; } };
class Solution_1 { public: vector<int> getRow(int rowIndex) { vector<vector<int>> f(2, vector<int>(rowIndex + 1)); for (int i = 0; i <= rowIndex; i ++) { f[i & 1][0] = f[i & 1][i] = 1; for (int j = 1; j < i; j ++) { f[i & 1][j] = f[i - 1 & 1][j - 1] + f[i - 1 & 1][j]; } }
return f[rowIndex & 1]; } };
int main() { Solution solution; vector<int> test_cases = { 3, 0, 1 };
for (auto& numRows : test_cases) { cout << "Input: " << numRows << endl; cout << "Output: "; vector<int> result = solution.getRow(numRows); for (const auto& num : result) { cout << num << " "; } cout << endl; }
return 0; }
|