首页 > 代码库 > leetcode 118. Pascal's Triangle && leetcode 119. Pascal's Triangle II
leetcode 118. Pascal's Triangle && leetcode 119. Pascal's Triangle II
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]]
nextline[j] = currentline[j] + currentline[j+1]
1 vector<vector<int> > generate(int numRows) 2 { 3 vector<vector<int> > pascal; 4 vector<int> line; 5 6 if (numRows <= 0) 7 return pascal; 8 9 line.push_back(1);10 pascal.push_back(line);11 if (numRows == 1)12 return pascal;13 14 for (int i = 1; i < numRows; i++)15 {16 vector<int> nextLine;17 18 nextLine.push_back(1);19 for (int j = 0; j < i - 1; j++)20 nextLine.push_back(line[j] + line[j + 1]);21 nextLine.push_back(1);22 pascal.push_back(nextLine);23 line = nextLine;24 }25 26 return pascal;27 }
Given an index k, return the kth row of the Pascal‘s triangle.
For example, given k = 3,
Return [1,3,3,1]
.
Note:
Could you optimize your algorithm to use only O(k) extra space?
1 vector<int> getRow(int rowIndex) 2 { 3 vector<int> line; 4 vector<int> nextline; 5 int numRows = rowIndex + 1; 6 7 if (numRows <= 0) 8 return line; 9 10 line.push_back(1);11 if (numRows == 1)12 return line;13 14 for (int i = 1; i < numRows; i++)15 {16 nextline.push_back(1);17 for (int j = 0; j < i - 1; j++)18 nextline.push_back(line[j] + line[j + 1]);19 nextline.push_back(1);20 line = nextline;21 nextline.clear();22 }23 24 return line;25 }
leetcode 118. Pascal's Triangle && leetcode 119. Pascal's Triangle II
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。