题目描述:

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]
]

 

本题要我们输入一个整数(行数),返回二维数组形式的杨辉三角(帕斯卡三角)。

解题思路:

因为杨辉三角中每一行的数都是上一行两个数之和。知道了这点我们可以用递归的形式实现这种求解方式。

代码:

 1 class Solution {
 2 public:
 3     void createTriangle(vector<vector<int>>& nums,int numRows){
 4         if(numRows==0)
 5         //行数为0的情况
 6             return;
 7         if(numRows==1){
 8         //行数为1的情况把1加到三角中
 9             vector<int> temp(1,1);
10             nums.push_back(temp);
11             return;
12         }
13         createTriangle(nums,numRows-1);//因为是从n=1开始的,所以要先递归
14         vector<int> temp(numRows);//创建一维数组
15         for(int i=0;i<numRows;i++){
16             if(i==0||i==numRows-1)
17             //最左和最右的数是特别的,要单独赋值
18                 temp[i]=1;
19             else
20                 temp[i]=nums[numRows-2][i]+nums[numRows-2][i-1];
21         }
22         nums.push_back(temp);//把一维数组加到二维数组中
23     }
24     vector<vector<int>> generate(int numRows) {
25         vector<vector<int>> result;
26         createTriangle(result,numRows);
27         return result;
28     }
29 };

 

 

 

posted on 2018-02-11 21:48  宵夜在哪  阅读(102)  评论(0编辑  收藏  举报