leetcode118/119. 杨辉三角
leetcode118. 杨辉三角1:
题目描述:
给定一个非负整数 numRows,生成杨辉三角的前 numRows 行。
示例:
输入:5
输出:[
[1],
[1, 1],
[1, 2, 1],
[1, 3, 3, 1],
[1, 4, 6, 4, 1]
]
#include<iostream> #include<vector> using namespace std; class Solution{ public: vector<vector<int>> generate(int numRows){ vector<vector<int>> vec; if(numRows == 0) return vec; else if(numRows <= 2){ for(int i = 0; i < numRows; ++i){ vector<int> smallVec(i+1, 1); vec.push_back(smallVec); } } else if(numRows > 2){ vec = generate(numRows-1); vector<int> smallVec(numRows, 1); for(int i=0;i<vec[numRows-2].size()-1;++i){ smallVec[i+1] = vec[numRows-2][i] + vec[numRows-2][i+1]; } vec.push_back(smallVec); } return vec; } }; int main(){ Solution solution; int count; cin>>count; vector<vector<int>> vec; vec = solution.generate(count); int row = vec.size(); int collumn = vec[0].size(); for(int i=0; i<row; ++i){ for(int j=0; j<collumn; ++j){ cout<<vec[i][j]<<" "; } } cout<<endl; return 0; }
leetcode119. 杨辉三角2
题目描述:
给定一个非负索引 k,其中 k ≤ 33,返回杨辉三角的第 k 行
示例:
输入:3
输出: [1, 3, 3, 1]
#include<iostream> #include<vector> using namespace std; class Solution{ public: vector<int> getRow(int rowIndex){ vector<int> vec(rowIndex + 1, 1); if(rowIndex <= 1) return vec; else if(rowIndex > 1){ vector<int> pastVec; pastVec = getRow(rowIndex - 1); for(int i=1; i<vec.size()-1; ++i){ vec[i] = pastVec[i-1] + pastVec[i]; } } return vec; } }; int main(){ Solution solution; vector<int> vec; int rowIndex; cin>>rowIndex; vec = solution.getRow(rowIndex); for(int i=0; i<vec.size(); ++i){ cout<<vec[i]<<" "; } cout<<endl; return 0; }