[leetcode] 118. Pascal's Triangle
2016-07-27 16:08
405 查看
Given numRows, generate the first numRows of Pascal's triangle.
For example, given numRows = 5,
Return
这道题是生成杨辉三角的前n行数据,题目难度为Easy。
杨辉三角相信大家都不陌生,每行首尾数字为1,其他部分数字为它两肩上两个数字之和,具体代码:class Solution {
public:
vector<vector<int>> generate(int numRows) {
vector<vector<int>> ret(numRows);
for(int i=0; i<numRows; ++i) {
ret[i].push_back(1);
for(int j=1; j<i; ++j)
ret[i].push_back(ret[i-1][j-1] + ret[i-1][j]);
if(i) ret[i].push_back(1);
}
return ret;
}
};
For example, given numRows = 5,
Return
[ [1], [1,1], [1,2,1], [1,3,3,1], [1,4,6,4,1] ]
这道题是生成杨辉三角的前n行数据,题目难度为Easy。
杨辉三角相信大家都不陌生,每行首尾数字为1,其他部分数字为它两肩上两个数字之和,具体代码:class Solution {
public:
vector<vector<int>> generate(int numRows) {
vector<vector<int>> ret(numRows);
for(int i=0; i<numRows; ++i) {
ret[i].push_back(1);
for(int j=1; j<i; ++j)
ret[i].push_back(ret[i-1][j-1] + ret[i-1][j]);
if(i) ret[i].push_back(1);
}
return ret;
}
};
相关文章推荐
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- leetcode----Longest Substring Without Repeating Characters
- [LeetCode]47 Permutations II
- [LeetCode]65 Valid Number
- [LeetCode]123 Best Time to Buy and Sell Stock III
- [LeetCode] String Reorder Distance Apart
- [LeetCode] Sliding Window Maximum
- [LeetCode] Find the k-th Smallest Element in the Union of Two Sorted Arrays
- [LeetCode] Determine If Two Rectangles Overlap
- [LeetCode] A Distance Maximizing Problem
- leetcode_linearList
- leetcode_linearList02
- 021-Merge Two Sorted Lists(合并两个排好序的单链表);leetcode
- LeetCode[Day 1] Two Sum 题解
- LeetCode[Day 2] Median of Two Sorted Arrays 题解
- LeetCode[Day 3] Longest Substring Without... 题解
- LeetCode [Day 4] Add Two Numbers 题解