问题

该文章的最新版本已迁移至个人博客【比特飞】,单击链接 https://www.byteflying.com/archives/3688 访问。

给定一个非负整数 numRows,生成杨辉三角的前 numRows 行。

在杨辉三角中,每个数是它左上方和右上方的数的和。

输入: 5

输出:

[

     [1],

    [1,1],

   [1,2,1],

  [1,3,3,1],

 [1,4,6,4,1]

]


Given a non-negative integer numRows, generate the first numRows of Pascal's triangle.



In Pascal's triangle, each number is the sum of the two numbers directly above it.

Input: 5

Output:

[

     [1],

    [1,1],

   [1,2,1],

  [1,3,3,1],

 [1,4,6,4,1]

]


示例

该文章的最新版本已迁移至个人博客【比特飞】,单击链接 https://www.byteflying.com/archives/3688 访问。

public class Program {

    public static void Main(string[] args) {
var res = Generate(5); ShowArray(res); Console.ReadKey();
} private static void ShowArray(IList<IList<int>> array) {
foreach(var num in array) {
foreach(var num2 in num) {
Console.Write($"{num2} ");
}
Console.WriteLine();
}
Console.WriteLine();
} private static IList<IList<int>> Generate(int numRows) {
if(numRows == 0) {
return new int[][] { };
}
int[][] res = new int[numRows][];
for(int i = 0; i < res.Length; i++) {
res[i] = new int[i + 1];
}
res[0][0] = 1;
for(int i = 1; i < numRows; i++) {
res[i][0] = 1;
for(int j = 1; j < i + 1; j++) {
if(j >= i) {
res[i][j] = res[i - 1][j - 1];
} else {
res[i][j] = res[i - 1][j - 1] + res[i - 1][j];
}
}
}
return res;
} }

以上给出1种算法实现,以下是这个案例的输出结果:

该文章的最新版本已迁移至个人博客【比特飞】,单击链接 https://www.byteflying.com/archives/3688 访问。

1
1 1
1 2 1
1 3 3 1
1 4 6 4 1

分析:

显而易见,以上参考算法在最坏的情况下的时间复杂度为:  ,空间复杂度也为:  。

最新文章

  1. [Java 基础]基础语法
  2. Struts2之Action
  3. HTTP协议,操作方法的幂等、安全性
  4. DataTable.Compute方法使用实例
  5. dbms_sql包的用法
  6. CCF 201312-2 ISBN号码 (水题)
  7. asp 文件上传(无组件上传)
  8. [置顶] 技术人血泪史:七种IT失误让你直接走人
  9. 使用WMI控制Windows进程 和服务
  10. CentOS 7将Python 2.X.X升级到Python 3.X.X
  11. The Last
  12. springboot解决跨域问题(Cors)
  13. 2018-2019-2 网络对抗技术 20165328 Exp4 恶意代码分析
  14. python 集成cython 简单测试
  15. 十、uboot 代码流程分析---run_main_loop
  16. 基于【字节】操作的IO接口:InputStream、OutputStream
  17. div + css 样式连接
  18. My simplified pickit2 clone
  19. JVM 方法调用之静态分派
  20. Hadoop Reducer个数设置

热门文章

  1. Java8——Stream流
  2. idea 项目启动console卡在Connected to the target VM, address: &#39;127.0.0.1:51140&#39;, transport: &#39;socket&#39;不动了
  3. Go Pentester - HTTP CLIENTS(1)
  4. Ethical Hacking - Web Penetration Testing(11)
  5. Python实现初始化不同的变量类型为空值
  6. Monster Audio 使用教程(四)Wifi 远程遥控
  7. 为什么Python适合初学者,一般要学习多久
  8. 04爬取拉勾网Python岗位分析报告
  9. spring 循环依赖的一次 理解
  10. Qt_Demo_4:汽车管理系统