您的位置:首页 > 编程语言 > C语言/C++

Leetcode_pascals-triangle-ii (updated c++ and python version)

2014-03-24 16:21 489 查看
地址:http://oj.leetcode.com/problems/pascals-triangle-ii/

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(k)的额外空间,所以Leetcode_pascals-triangle那样用了O(k平方)的方法是不行的。

其实杨辉三角返回的是组合数,比如第五行返回的是C(5, 0), C(5, 1), C(5, 2), C(5, 3), C(5, 4), C(5, 5)六个数。C(X, Y)中X是组合数的下标,Y 是组合数上标。

组合数的概念:http://zh.wikipedia.org/zh/%E7%BB%84%E5%90%88%E6%95%B0%E5%AD%A6

代码写的臃肿不堪入目,等以后写第二遍第三遍时候再优化一下。

注意相乘时候上溢出问题。

参考代码:

class Solution {
public:
vector<int> getRow(int rowIndex) {
vector<int>res;
if(!rowIndex)
{
res.push_back(1);
return res;
}
else if(rowIndex==1)
{
res.push_back(1);
res.push_back(1);
return res;
}
else
{
res.push_back(1);
for(int i = 1; i <= rowIndex/2; ++i)
{
if(i==1)
{
res.push_back(rowIndex);
}
else
{
long long int num = 1, j=0, k=i;
while(j<i)
{
num*=(rowIndex-j++);
if(k>=2 && !(num%k))
{
num/=k--;
}
}
while(k>=2)
{
num/=k--;
}
res.push_back(num);
}
}
vector<int>backupvec(res.begin(), res.end());
if(!(rowIndex%2))
{
backupvec.pop_back();
}
res.insert(res.end(), backupvec.rbegin(), backupvec.rend());

}
}
};


//SECOND TRIALclass Solution {public:    vector<int> getRow(int rowIndex) {        vector<int>v1(rowIndex, 1), v2(rowIndex+1, 1);        if(rowIndex<=1)            return v2;        for(int i = 2; i<=rowIndex; ++i)        {            for(int j = 1; j<i; ++j)                v2[j] = v1[j-1] + v1[j];            v1 = v2;        }        return v2;    }};

#Attention for python's list assignment#use a = b[:] instead of a = bclass Solution:    # @return a list of integers    def getRow(self, rowIndex):        v1 = [1]*rowIndex         v2 = [1]*(rowIndex+1)        if rowIndex<=1:            return v2        for i in range(2, rowIndex+1):            for j in range(1, i):                v2[j] = v1[j-1] + v1[j]            v1 = v2[:-1]        return v2
                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: