标签:style blog http color io os for strong sp
Pascal‘s Triangle
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] ]
这题别想用通项公式做,n choose m里面的连乘必然溢出,老老实实逐层用定义做。
class Solution { public: vector<vector<int> > generate(int numRows) { vector<vector<int> > result; if(numRows == 0) { //nothing } else if(numRows == 1) { //第0层 vector<int> cur; cur.push_back(1); result.push_back(cur); } else { //第0层 vector<int> cur; cur.push_back(1); result.push_back(cur); for(int n = 1; n < numRows; n ++) {//用<n choose m>的通项公式来做肯定溢出,所以只能用加法做 vector<int> cur; //头 cur.push_back(1); //中间元素是上层两元素相加 for(int i = 0, j = 1; j < n; i++, j++) { vector<int> pre = result[result.size()-1]; cur.push_back(pre[i]+pre[j]); } //尾 cur.push_back(1); result.push_back(cur); } } return result; } };
标签:style blog http color io os for strong sp
原文地址:http://www.cnblogs.com/ganganloveu/p/4021183.html