首页 > 其他 > 详细

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

时间:2019-06-15 10:11:52      阅读:139      评论:0      收藏:0      [点我收藏+]

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.

技术分享图片
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;
}

 

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

原文:https://www.cnblogs.com/hu-19941213/p/11026546.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!