Given a non-negative integer numRows, generate the first numRows of Pascal's triangle.
題意
給定一個非負整數?numRows,生成楊輝三角的前?numRows?行。
輸入: 5
輸出:
[
?????[1],
????[1,1],
???[1,2,1],
??[1,3,3,1],
?[1,4,6,4,1]
]
解題
class?Solution?{public:vector<vector<int>> generate(int?numRows) {vector<vector<int>> result;if?(numRows == 0) {return?{};
????}vector<int> tempRes = { 1?};//第一行,初始行
????result.push_back(tempRes);for?(int?index = 2; index <= numRows; ++index) {//利用result的最后一行進行迭代
??????tempRes = vector<int>(index, 1);//重新設定tempResfor?(int?i = 1; i < index - 1; ++i) {//利用上一行迭代下一行//result[index - 2][i - 1]上一行的第i-1個位置,圖中的左上方//result[index - 2][i]是表示上一行第i個位置,圖中的右上方
????????tempRes[i] = result[index - 2][i - 1] + result[index - 2][i];
??????}
??????result.push_back(tempRes);//此行迭代完畢放入結果
????}return?result;
??}
};
好了,今天的文章就到這里,如果覺得有所收獲,請順手點個在看或者轉發吧,你們的支持是我最大的動力。上期推文:LeetCode1-100題匯總,希望對你有點幫助!LeetCode刷題實戰101:對稱二叉樹LeetCode刷題實戰102:二叉樹的層序遍歷LeetCode刷題實戰103:二叉樹的鋸齒形層次遍歷LeetCode刷題實戰104:二叉樹的最大深度LeetCode刷題實戰105:從前序與中序遍歷序列構造二叉樹LeetCode刷題實戰106:從中序與后序遍歷序列構造二叉樹LeetCode刷題實戰107:二叉樹的層次遍歷 IILeetCode刷題實戰108:將有序數組轉換為二叉搜索樹LeetCode刷題實戰109:有序鏈表轉換二叉搜索樹LeetCode刷題實戰110:平衡二叉樹LeetCode刷題實戰111:二叉樹的最小深度LeetCode刷題實戰112:路徑總和LeetCode刷題實戰113:路徑總和 II
LeetCode刷題實戰114:二叉樹展開為鏈表
LeetCode刷題實戰115:不同的子序列
LeetCode刷題實戰116:填充每個節點的下一個右側節點指針
LeetCode刷題實戰117:填充每個節點的下一個右側節點指針 II