您的位置:首页 > 其它

Leetcode Problem.118—Pascal's Triangle

2015-06-03 15:25 337 查看
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]
]


My C++ solution!

vector<vector<int>> generate(int numRows) 
    {
        vector<vector<int>>result;
        result.resize(numRows);
        if(numRows==0)
           return result;
        if(numRows==1)
          {
           result[0].assign(1,1);
           return result;
          }
        if(numRows>=2)
        {
        result[0].assign(1,1);
        for(int i=1;i<numRows;i++)
          {
              vector<int>pre(result[i-1]);
              vector<int>temp;
              temp.resize(i+1);
              temp[0]=1;
              for(int j=1;j<i/2+1;j++)
                {
                    temp[j]=pre[j-1]+pre[j];
                }
              for(int j=i/2+1;j<i+1;j++)
                {
                    temp[j]=temp[i-j];
                }
              result[i]=temp;
          }
        }
          return result;
        
    }
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: