leetcode 生成杨辉三角形, 118 119 Pascal's Triangle 1,2
2015-07-26 20:20
567 查看
Given numRows, generate the first numRows of Pascal's triangle.
For example, given numRows = 5,
Return
解决方案:
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
Note:
Could you optimize your algorithm to use only O(k) extra space?
我的解决方案:
从没一行的倒数第二个算起,往前面逆推:
递归的解决方案:
python 解决方案:
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
相关文章推荐
- HDU 1099 Lottery 乐透彩
- Codevs3945 完美拓印
- 长度单位与内外边距
- windows 控制面板
- 将十进制数转换为二进制数
- leetcode 生成杨辉三角形, 118 119 Pascal's Triangle 1,2
- [Leetcode 142] Linked List Cycle II
- [LeetCode]Binary Tree Right Side View
- 按键事件在java framework中的流程
- Head First设计模式悟道
- 常用的汉字,用于获得随机图片
- HDU 5310 Souvenir
- 找短板1:柱状图中的最大矩阵面积
- HDU 2222 Keywords Search(AC自动机)
- c语言 模拟 库函数 strstr()函数
- 埃氏筛法(快速筛选n以内素数的个数)
- UVA 299 Train Swapping
- hdu 5306 Gorgeous Sequence(暴力线段树)(好题)
- Loadrunner关于页面检查的几个函数详解
- tomcat启动成功外网无法访问