leetcode_118 Pascal Triangle
2016-04-10 22:36
316 查看
题目分析:
给定整数n,生成杨辉三角的前n行
解题思路:
依据杨辉三角性质求解
杨辉三角性质:
1)每行第一个元素和最后一个元素值为1;
2)每行非第一个和最后一个元素值为:tri[i][j] = tri[i-1][j-1] + tri[i-1][j]
实现程序
给定整数n,生成杨辉三角的前n行
解题思路:
依据杨辉三角性质求解
杨辉三角性质:
1)每行第一个元素和最后一个元素值为1;
2)每行非第一个和最后一个元素值为:tri[i][j] = tri[i-1][j-1] + tri[i-1][j]
实现程序
class Solution { public: vector< vector<int> > generate(int numRows) { vector< vector<int> > result; // 特殊情况处理 if (numRows == 0) return result; int i = 0; int j = 0; for (int i = 0; i < numRows; i++) { vector<int> temp; for (int j = 0; j < i + 1; j++) { // 放置每行的第一个元素和最后一个元素 if (j == 0 || j == i) temp.push_back(1); // 依据杨辉三角性质tri[i][j] = tri[i-1][j-1]存放每行的其他数据 else temp.push_back(result[i - 1][j - 1] + result[i - 1][j]); } // 存放一行元素数据 result.push_back(temp); } // 返回最终结果 return result; } };
相关文章推荐
- 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 题解