2017.11.14 LeetCode

来源:互联网 发布:个人发卡网源码授权 编辑:程序博客网 时间:2024/06/05 07:11
最近很忙,又有期中考试,事偏多,耽误了几天,下次一定要注意,加油!

118. Pascal’s Triangle

Description

Given numRows, generate the first numRows of Pascal’s triangle.

For example, given numRows = 5,
Return

[
[1],
[1,1],
[1,2,1],
[1,3,3,1],
[1,4,6,4,1]
]
题意: 打印杨辉三角

分析: 这个直接根据性质模拟的略

参考函数

class Solution {public:    vector<vector<int>> generate(int numRows) {        vector<vector<int> > res;        vector<int> t;        for(int i = 0;i < numRows;i++) {            t.push_back(1);            for(int j = 1;j < i;j++) {                int s = res[i-1][j-1] + res[i-1][j];                t.push_back(s);            }            if(i > 0)                t.push_back(1);            res.push_back(t);            t.clear();        }        return res;    }};

119. Pascal’s Triangle II

Description

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?

题意 : 打印第杨辉三角中的第k+1行

分析: 根据组合数中的性质,我们知道 C(n,m) = C(n,m-1)*(n-m+1)/m,直接根据公式即可

参考函数

class Solution {public:    vector<int> getRow(int rowIndex) {        vector<int> res(rowIndex+1);        res[0] = 1;        for(int i = 1;i <= rowIndex;i++) {            long long t = (int)res[i-1]*1ll*(rowIndex-i+1)/i;            res[i] = t;        }        return res;    }};