Pascal's Triangle <LeetCode>

本文介绍了一种基于动态规划思想生成帕斯卡三角形的方法。通过简单的算法实现,可以生成指定层数的帕斯卡三角形。适用于高中数学教学及计算机科学入门课程。

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

思路:首先这道题是有规律可循的,规律很简单(有点动态规划思想的感觉),这里就不说了,因为高中的时候就学过了,代码如下:
 1 class Solution {
 2 public:
 3     vector<vector<int>>  result;
 4     vector<vector<int> > generate(int numRows) {
 5         result.clear();
 6         int B[numRows];
 7         int C[numRows];
 8         int count=0;
 9         for(int i=0;i<numRows;i++)
10         {
11             count=0;
12             vector<int>  temp;
13             temp.push_back(1);
14             B[count]=1;
15             for(int j=1;j<i;j++)
16             {
17                 count++;
18                 temp.push_back(B[j-1]+B[j]);
19                 C[count]=B[j-1]+B[j];
20             }
21             if(i>0)  
22             {
23                 temp.push_back(1);
24             
25                 B[count+1]=1;
26             }
27             for(int j=1;j<i;j++)
28             {
29                 B[j]=C[j];
30             }
31             result.push_back(temp);
32         }
33         return result;
34     }
35 };

 

转载于:https://www.cnblogs.com/sqxw/p/3953907.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值