码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode 119 Pascal's Triangle II

时间:2017-10-07 22:09:32      阅读:153      评论:0      收藏:0      [点我收藏+]

标签:src   cal   for   公式   turn   code   dex   ges   tco   

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?

  • 要求空间复杂度为 O(n )
  • 和上题不同,此题是从0开始,和数组下标一致

 

1. 通过一维数组来模拟杨辉三角逐渐变换的情况

技术分享

 

class Solution {
public:
vector<int> getRow(int numRows) {
vector<int>result(numRows+1,0);
result[0] = 1;
for (int i=1; i <= numRows; i++)
{
for (int j=i; j >= 1 ;j--)
{
result[j] += result[j-1];
}
}
return result;
}
};

;

 

 2.数学公式

class Solution {
public:
    vector<int> getRow(int numRows) {
        vector<int>result(numRows+1,0);
        result[0] = result[numRows] = 1;
        for (int i=1; i < (numRows+2)/2 ; i++)
        {
           result[i] = result[numRows-i] = result[i-1] * (numRows - i + 1) /i;
        }
        return result;
    }
};

  3.关于杨辉三角的规律

  技术分享

 

leetcode 119 Pascal's Triangle II

标签:src   cal   for   公式   turn   code   dex   ges   tco   

原文地址:http://www.cnblogs.com/sxy-798013203/p/7635841.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!