leetcode-118-Pascal's Triangle 基础题
来源:互联网 发布:炒股日记软件 编辑:程序博客网 时间:2024/05/18 02:59
问题
题目:[leetcode-118]
思路
基础题,杨辉三角。
代码(c++实现)
//c++ versionclass Solution {public: vector<vector<int>> generate(int numRows) { vector< vector<int> > ret; for( int i = 0; i < numRows; ++i ) { vector< int > t; if( !i ) { t.push_back(1); ret.push_back(t); } else { for( int j = 0; j <= i; ++j ) { if( !j || j == i ) t.push_back(1); else t.push_back(ret[i-1][j-1] + ret[i-1][j]); } ret.push_back(t); } } return ret; }};
下面用c实现,这个题思路不难。不过c的实现还花了我点时间,主要是题意的理解问题。其实指针本省的使用没问题,但是对于题目要怎么样用指针没有理解好。主要是对columnSizes的理解,*columnSizes是一个一维数组。存储每一行的大小。这没有问题,关键是这个变量本省有没有开辟空间我不知道,起初以为就是一个指针,连这个变量也没有开辟。所以,在代码中开辟了三块内存空间:
- tri
- columnSizes(这一块的开辟导致程序的错误)
- *columnSizes
按照题目的意思,第二块的开辟是没有必要的。这个从注释最后一句话应该是可以得到的。所以,对题目的理解还是要仔细。
代码1(c实现)
//c version/** * Return an array of arrays. * The sizes of the arrays are returned as *columnSizes array. * Note: Both returned array and *columnSizes array must be malloced, assume caller calls free(). */int** generate(int numRows, int** columnSizes) { if( numRows <= 0 ) return NULL; int** tri = (int**)malloc( sizeof(int*) * numRows ); if( !tri ) return NULL; *columnSizes = (int*)malloc( sizeof(int) * numRows ); if( !(*columnSizes) ) return NULL; for( int i = 0; i < numRows; ++i ) { tri[i] = (int*)malloc( sizeof(int) * (i+1) ); if(!tri[i]) return NULL; *((*columnSizes)+i) = i + 1; for( int j = 0; j <= i; ++j ) { if( !j || j == i ) tri[i][j] = 1; else tri[i][j] = tri[i-1][j-1] + tri[i-1][j]; } } return tri;}
0 0
- leetcode-118-Pascal's Triangle 基础题
- Leetcode 第118题 Pascal's Triangle
- LeetCode 118: Pascal's Triangle
- LeetCode(118)Pascal's Triangle
- LeetCode: Pascal's Triangle [118]
- LeetCode 118 Pascal's Triangle
- LeetCode 118 Pascal's Triangle
- [leetcode 118] Pascal's Triangle
- leetCode #118 Pascal's Triangle
- LeetCode 118 :Pascal's Triangle
- leetcode-118 Pascal's Triangle
- leetcode || 118、Pascal's Triangle
- LeetCode 118:Pascal's Triangle
- Leetcode[118]-Pascal's Triangle
- LeetCode---(118)Pascal's Triangle
- [leetcode 118]Pascal's Triangle
- LeetCode 118 Pascal's Triangle
- leetcode[118]:Pascal's Triangle
- navicat MySQL 导出数据时出现1577错误解决方法
- cocos2d-x给Text,imageView添加侦听
- Linux常用命令
- OC中的占位符
- Failed to execute aapt
- leetcode-118-Pascal's Triangle 基础题
- 将放入list中的姓名号码自动写入系统通讯录
- 开始搭建Appium自动化测试环境之安装1.1
- [Gradle]Error:java.lang.OutOfMemoryError: Java heap space . Please assign more memory to Gradle in t
- 反对项目经理在项目计划中把程序员标志为“资源”
- Saving Key-Value Sets 官方文档翻译
- LingPipe深度剖析
- 银行卡验证
- Python中使用正则表达式