Pascal's Triangle

news/2024/7/5 3:16:48

帕斯卡三角形,主要考察vector的用法。

vector<vector<int> > generate(int numRows){vector<vector<int> > result;vector<int> tmp;result.clear();tmp.clear();int i,j;if(numRows == 0)return result;else if(numRows == 1){tmp.push_back(1);result.push_back(tmp);return result;}else if(numRows == 2){tmp.push_back(1);result.push_back(tmp);tmp.push_back(1);result.push_back(tmp);return result;}else{tmp.push_back(1);result.push_back(tmp);tmp.push_back(1);result.push_back(tmp);for(i = 2; i < numRows; i++){tmp.clear();            tmp.push_back(1);for(j = 1;j<=i-1;j++){tmp.push_back(result[i-1][j-1]+result[i-1][j]);}tmp.push_back(1);result.push_back(tmp);            }}return result;
}

 上次怎么写这个麻烦,第二次写得简练许多

 1     vector<vector<int> > generate(int numRows){
 2         vector<vector<int> > res;
 3         vector<int> tmp, last;
 4         if(numRows == 0)
 5             return res;
 6         int i,j; 
 7         for(i = 0; i < numRows; i++){
 8             tmp = vector<int>(i+1, 0);
 9             tmp[0] = 1;
10             tmp[i] = 1;
11             for(j = 1; j < i; j++)
12                 tmp[j] = last[j-1] + last[j];
13             res.push_back(tmp);
14             last = tmp;
15         }
16         return res;
17     }

 

转载于:https://www.cnblogs.com/waruzhi/p/3317753.html


http://lihuaxi.xjx100.cn/news/249559.html

相关文章

替换 RHEL5的yum源为CentOS5源,亲测线上系统可用

最近安装nagiospnp&#xff0c;各种依赖包啊。rrdtool肿么装的这么费劲&#xff0c;后来实在扛不住了&#xff0c;还是修改rhel的源吧&#xff0c;把yum源搞成centos的不就ok了&#xff01;哈哈。然后就从网上一顿猛搜&#xff0c;发现“Ayou”老师的文章很靠谱&#xff0c;很有…

#天天复制,今天写一个# 把文字转为图片

/*** 把文字转为图片* * param text* 要写的内容* throws IOException*/public static void textToImg(String text) throws IOException {int len text.length();int fontSize 1000;int width len * fontSize;Font font new Font("楷体", Font2D.NAT…

关于Linux服务器磁盘空间占满问题的解决方法

下面给大家分享一篇关于Linux服务器磁盘占满问题解决方法&#xff08;/dev/sda3 满了&#xff09;&#xff0c;需要的的朋友参考下吧下面我们一起来看一篇关于Linux服务器磁盘占满问题解决&#xff08;/dev/sda3 满了&#xff09;&#xff0c;希望碰到此类问题的人能带来帮助。…

未来的程序员面临着怎样的职业变化

作为程序员&#xff0c;我们总是身处于如万花筒般变化无常的技术世界里。我们可能也是那群能够最早感知到科技变化所带来巨大影响的人。然而&#xff0c;面对这一波又一波向我们袭来的技术变革&#xff0c;我们是否也能从中窥见一丝规律&#xff0c;从而使自己更好地应对未来呢…

地址本在不同手机间的迁移

更换手机时最烦人的莫过于迁移地址本了&#xff0c;近来又迎来了换工作&#xff0c;换手机&#xff0c;先将地址本迁移的方法总结如下&#xff1a; 1&#xff09;通用方法 功能手机上不能自己写程序的话&#xff0c;迁移起来没有什么好办法&#xff0c;只能先把地址本复制到SIM…

关于AD编程的一些资料

有人问我怎样在.NET下操作AD对象&#xff0c;找了些资料和Sample&#xff0c;留作备用。 .NET Framework Class Library: System.DirectoryServices Namespace http://msdn.microsoft.com/library/en-us/cpref/html/frlrfsystemdirectoryservices.asp How to poll for changes …

我的户外生活

因为一直向往着有一次川藏之旅&#xff0c;但是一直没机会&#xff0c;所以很遗憾。但是最近开始准备这些了&#xff0c;所以开始搜罗户外的用品了&#xff0c;我也顺便给大家推荐推荐&#xff0c;因此在博客中开了这个专栏。先来个骆驼官方旗舰店&#xff0c;大家可选购http:/…

一个完整的大作业

1.选一个自己感兴趣的主题。网址为http://news.gzcc.cn/html/xiaoyuanxinwen/ 2.网络上爬取相关的数据 import requests import re from bs4 import BeautifulSoup urlhttp://news.gzcc.cn/html/xiaoyuanxinwen/ resrequests.get(url) res.encodingutf-8 soupBeautifulSoup(res…