问题

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

给定一个非负索引 k,其中 k ≤ 33,返回杨辉三角的第 行。

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

输入: 3

输出: [1,3,3,1]

你可以优化你的算法到 O(k) 空间复杂度吗?


Given a non-negative index k where k ≤ 33, return the kth index row of the Pascal's triangle.

Note that the row index starts from 0.



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

Could you optimize your algorithm to use only O(k) extra space?

Input: 3

Output: [1,3,3,1]


示例

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

public class Program {

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

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

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

1 4 6 4 1
1 5 10 10 5 1

分析:

显而易见,GetRow在最坏的情况下的时间复杂度为:  ,空间复杂度也为: ;

GetRow2在最坏的情况下的时间复杂度为:  ,由于使用一维数组空间复杂度为:  。

GetRow2方法可以根据杨辉三角的对称性优化,只需计算一半即可,其实现方法留给各位看官。

最新文章

  1. 淘宝WAP版小BUG分析
  2. oracle之trunc与round
  3. APP Widget的开发
  4. apache-flume-1.5.0-bin windows
  5. Android中dp和px之间进行转换
  6. extjs文件上传
  7. Oracle EBS-SQL (BOM-10):检查有BOM无计划员的数据.sql
  8. SQL Server 一些重要视图3
  9. Linux JDK+TOMCAT+MYSQL+redis 安装日志
  10. ASP.NET MVC5(三):表单和HTML辅助方法
  11. angularjs+ionic+&#39;h5+&#39;实现二维码扫描功能
  12. DataPipeline丨金融行业如何统一管理单个任务下所有API的同步情况
  13. SqlServer 更改数据库名称
  14. 【jquery】checkbox
  15. python之排列组合测试
  16. linux中tomcat内存溢出解决办法
  17. OO第三次阶段总结
  18. 2018软工实践—Beta冲刺(1)
  19. (转)Unity3D命令行Build
  20. mac 第一次安装mysql 5.7.12 不知道root 密码的解决办法

热门文章

  1. DirectX11 With Windows SDK--34 位移贴图
  2. Ethical Hacking - Web Penetration Testing(7)
  3. JAVA 面向对象 三大特征:继承
  4. ant design pro 实战 : 使用 ztree
  5. 在ASP.NET Core中创建自定义端点可视化图
  6. Aliyun Linux2安装Docker
  7. 萌新学渗透系列之Hack The Box_Legacy
  8. Letex中表格问题
  9. 修改docker中mysql登入密码(包括容器内和本地远程登入的密码)
  10. RDD和Dataframe相互转换