Pascal's Triangle

Source: Internet
Author: User

GivenNumrows, Generate the firstNumrowsOf Pascal's triangle.

For example, givenNumrows= 5,
Return

[     [1],    [1,1],   [1,2,1],  [1,3,3,1], [1,4,6,4,1]]

 1 class Solution { 2 public: 3     vector<vector<int> > generate(int numRows) { 4         vector<vector<int>> sols; 5         if(numRows==0)return sols; 6         vector<int> pre(1,1); 7         sols.push_back(pre); 8         for(int i=1;i<numRows;i++) 9         {10             vector<int> cur;11             cur.push_back(1);12             for(int j=1;j<i;j++)13             {14                cur.push_back(sols[i-1][j-1]+sols[i-1][j]);15             }16             cur.push_back(1);17             sols.push_back(cur);18         }19         return sols;20     }21 };
Pascal's triangle II

 

Given an indexK, ReturnKTh row of the Pascal's triangle.

For example, givenK= 3,
Return[1,3,3,1].

Note:
Cocould you optimize your algorithm to use onlyO(K) Extra space?

Idea: You can use an array by adding the following code.

 1 class Solution { 2 public: 3     vector<int> getRow(int rowIndex) { 4         vector<int> sols(1,1); 5         for(int i=1;i<rowIndex+1;i++) 6         { 7             sols.resize(i+1,0); 8             for(int j=sols.size()-1;j>=1;j--) 9             {10                 sols[j]=sols[j]+sols[j-1];//!!!!11             }12         }13         return sols;14         15     }16 };

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.