Tuesday, July 23, 2013

Pascal's triangle@leetcode

微博:http://www.weibo.com/cathyhwzn

刷题必备书籍:Cracking the Coding Interview: 150 Programming Questions and Solutions
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]
]
» Solve this problem

弱爆题没啥好说的,下标别搞错就行了。

class Solution {
public:
vector<vector<int> > generate(int numRows) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
vector<vector<int> > res;
if(!numRows) return res;
vector<int> sol;
sol.push_back(1);
res.push_back(sol);
sol.clear();
for(int i=1; i<numRows; i++)
{
for(int j=0; j<=i; j++)
{
if(j==0||j==i)
sol.push_back(res[i-1][0]);
else
sol.push_back(res[i-1][j-1]+res[i-1][j]);
}
res.push_back(sol);
sol.clear();
}
return res;
}
};

No comments:

Post a Comment

Leetcode 316. Remove Duplicate Letters

 这道题表面问的是如何删除重复,实际在问如何从多个字符选取一个保留,从而让整个字符串按升序排列。那么策略就是对于高顺位的字符比如‘a',就要选靠前位置的保留,而低顺位字符如’z'则应该尽量选取靠后位置保留。 算法大概思路:每看到一个字符,我们要决定是否保留 1. ...