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

解决方案:

vector<vector<int>> generate(int numRows) {
vector<vector<int>> res = {};
for (int i = 0; i < numRows; i++) {
res.push_back(vector<int>(i + 1, 1));
for(int j = 1; j < i; j++) {
res[i][j] = (res[i - 1][j] + res[i - 1][j - 1]);
}
}
return res; }

Pascal's Triangle II
Total Accepted: 46342
Total Submissions: 157260

Given an index k, return the kth row of the Pascal's triangle.

For example, given k = 3,

Return [1,3,3,1].

Note:

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

我的解决方案:

从没一行的倒数第二个算起,往前面逆推:

 vector<int> getRow(int rowIndex)
{
vector<int> result(rowIndex + 1, 1); for(int i = 1; i <= rowIndex; ++i)
{
for(int j = i - 1; j > 0; --j)
{
result[j] = result[j] + result[j - 1];
}
} return result;
}

递归的解决方案:

vector<int> getRow(int rowIndex) {
vector<int> result; if (rowIndex == 0) {
result.push_back(1); return result;
} else {
vector<int> vec = getRow(rowIndex - 1);
result.push_back(1);
for (size_t i = 0; i < vec.size() - 1; i++) {
result.push_back(vec[i] + vec[i+1]);
}
result.push_back(1);
}
}

python 解决方案:

class Solution:
# @param {integer} rowIndex
# @return {integer[]}
def getRow(self, rowIndex):
row = [1]
for i in range(1, rowIndex+1):
row = list(map(lambda x,y: x+y, [0]+row, row + [0]))
return row

最新文章

  1. is_null, empty, isset, unset对比
  2. 修改Excel2013默认模版(启动模版和新建Sheet模版)
  3. AFNetworking 之于 https 认证
  4. bower安装使用入门详情
  5. 轻松入门React和Webpack
  6. STM32单片机实现中断后不继续向下执行而是返回到main函数
  7. js set
  8. php parse_url 函数使用方法解析
  9. JqGrid动态改变列名
  10. JVM性能监控与故障处理命令汇总(jps、jstat、jinfo、jmap、jhat、jstack)
  11. Scrapy-redis&lt;数据库篇&gt;
  12. es定期删除数据
  13. 201771010126 王燕《面向对象程序设计(Java)》第十二周学习总结
  14. Tomcat配置文件Executor元素属性介绍
  15. shell脚本中gsub的应用
  16. bzoj2004 矩阵快速幂优化状压dp
  17. git 管理和存储二进制大文件
  18. php会话控制技术
  19. 常见Java问题
  20. c++泛型模板

热门文章

  1. Swift开发教程--怎样使UITableViewController背景透明
  2. Swift基础--定位
  3. Android学习JNI,使用JNI实现字符串加密
  4. nyoj--301--递推求值(经典矩阵运算)
  5. angular4(2-1)angular脚手架引入第三方类库(jquery)
  6. CSS3个人盲点总结【总结中..........】
  7. cell的重用
  8. Elasticsearch开发环境搭建(Eclipse\MyEclipse + Maven)
  9. 访问视频资源报错:Failed to load resource: net::ERR_CONNECTION_RESET
  10. Windows窗体应用布局详解