【LeetCode】17.Array and String — Pascal's Triangle II -帕斯卡三角-杨辉三角II

Given a non-negative index k where k ≤ 33, return the kth index row of the Pascal's triangle.

Note that the row index starts from 0.

【LeetCode】17.Array and String — Pascal's Triangle II -帕斯卡三角-杨辉三角II
In Pascal's triangle, each number is the sum of the two numbers directly above it.

Example:

Input: 3
Output: [1,3,3,1]

Follow up:

Could you optimize your algorithm to use only O(k) extra space?

与 I 不同,本题的主要区别在于对于空间复杂度有要求。

vector<int> getRow(int rowIndex)
{
    if (rowIndex == 0) return{ 1 };//对第一行和第二行做特殊处理
    if (rowIndex == 1) return{ 1,1 };
    vector<int>result1 = {1,1};//为了解决空间复杂度的问题,定义两个数组。
    vector<int>result2 = {1,1};
    int counter = rowIndex-1;
    while (counter) {
        for (int i = 0; i < result1.size()-1; i++)
        {
            result2.insert(result2.begin() + 1, result1[i] + result1[i + 1]);//在数组中间插入按规则计算出来的元素。
        }
        result1 = result2;
        result2 = { 1,1 };
        counter--;
    }
    return result1;
}

 

上一篇:Jonathan Richard Shewchuk的德劳内三角化生成器Triangle研读笔记


下一篇:OSG得到OSGB中几何体顶点、法向量、三角形数据并可视化