每天一道LeetCode-----杨辉三角
生活随笔
收集整理的這篇文章主要介紹了
每天一道LeetCode-----杨辉三角
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
Pascal’s Triangle
原題鏈接Pascal’s Triangle
楊輝三角,求出前n行的楊輝三角排列
楊輝三角的特點是triangle[i][j] = triangle[i-1][j-1] + triangle[i-1][j],越界的下標值為0
所以直接根據這個公式計算即可
代碼如下
class Solution { public:vector<vector<int>> generate(int numRows) {vector<vector<int>> res(numRows);if(numRows == 0) return res;res[0] = {1};for(int i = 1; i < numRows; ++i){res[i].reserve(i + 1);for(int j = 0; j < i + 1; ++j){int n = 0;/* 第一個j - 1會越界,直接設置為0 */n += (j > 0) ? res[i - 1][j - 1] : 0;/* 最后一個j會越界,直接設置為0 */n += (j < i) ? res[i - 1][j] : 0;res[i].push_back(n);}}return res;} };Pascal’s Triangle II
原題鏈接Pascal’s Triangle II
楊輝三角,找到第k行(從0開始),要求空間復雜度是O(k)
因為前k行每一行的元素個數都小于k+1,所以直接開辟k+1的數組空間,然后從第0行開始求,不斷改變數組元素,最后求得第k行
又因為求新的一行時會用到上一行的對應列元素和前一列元素,所以不能從左向右而應該從又向左求
代碼如下
class Solution { public:vector<int> getRow(int rowIndex) {vector<int> res(rowIndex + 1);res[0] = 1;for(int i = 1; i <= rowIndex; ++i){/* 從后往前求 */for(int j = i; j >= 0; --j){int n = 0;n += (j > 0) ? res[j - 1] : 0;n += (j < i) ? res[j] : 0;res[j] = n;}}return res;} };兩道題都是和楊慧三角有關,對著公式寫代碼就可以了
總結
以上是生活随笔為你收集整理的每天一道LeetCode-----杨辉三角的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Redis源码剖析(六)事务模块
- 下一篇: 每天一道LeetCode-----杨辉三