题目链接
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 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97
| #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]; } };
class Solution_2 { public: vector<int> getRow(int rowIndex) { vector<int> f(rowIndex+1, 0); f[0] = 1;
for (int i = 1; i <= rowIndex; i++) { for (int j = i; j >= 1; j--) { f[j] = f[j] + f[j-1]; } }
return f; } };
void printArray(const vector<int>& nums) { cout << "["; for (size_t i = 0; i < nums.size(); i++) { cout << nums[i]; if (i != nums.size() - 1) cout << ","; } cout << "]"; }
int main() { Solution solution; vector<int> rows_cases = { 3, 0, 1 };
for (int i = 0; i < rows_cases.size(); i++) { int rows = rows_cases[i]; vector<int> result = solution.getRow(rows);
cout << "Input: rowIndex = " << rows << endl; cout << "Output: "; printArray(result); cout << endl; }
return 0; }
|