乐扣118 杨辉三角/杨辉三角2
题目:
给定一个非负整数 numRows,生成杨辉三角的前 numRows 行。
class Solution {
public:
vector< vector<int> > generate(int numRows) {
vector<vector<int> > result;
int count=1;
while(count<=numRows)
{
std::vector<int> v;
if (count==1)
{
v.push_back(1);
}
else if (count==2)
{
v.push_back(1);
v.push_back(1);
}
else
{
v.push_back(1);
int t=count-2;
for (int i = 0; i < t; ++i)
{
//cout<<result[count-2][i]<<" "<<result[count-2][i+1]<<endl;
int mm=result[count-2][i]+result[count-2][i+1];
//cout<<mm<<endl;
v.push_back(mm);
}
v.push_back(1);
}
result.push_back(v);
for(int i=0;i<v.size();i++)
cout<<v[i]<<" ";
cout<<endl;
count++;
}
return result;
}
};
按照杨辉三角的定义去求
题目
给定一个非负索引 k,其中 k ≤ 33,返回杨辉三角的第 k 行
思路一:
按照组合数去求,杨辉三角的第n行可以看作组合数Cin,i从0到n
class Solution {
public:
int Comb(int N,int k)
{
int mx=max(i,n-i);
int mn=min(i,n-i);
long r1=1,r2=1;
for(long k=n;k>mx;k--)
r1*=k;
for(long int p=2;p<=mn;p++)
r2*=p;
long r=r1/r2;
//cout<<"n:"<<n<<"i:"<<i<<"result:"<<r<<endl;
return (int)r;
}
vector<int> getRow(int rowIndex) {
vector<int> result;
result.push_back(1);
if(rowIndex==0) return result;
else if(rowIndex==1)
{
result.push_back(1);
return result;
}
else
{
int half=rowIndex/2+1;
int n=rowIndex;
for(int i=1;i<half;i++)
result.push_back(Comb(n,i));
int p=(n%2==0)? (half-1):half;
for(int i=p-1;i>=0;i--)
result.push_back(result[i]);
return result;
}
}
};
本解法有一个问题,数据溢出,即使采用long类型,也是会产生溢出,但是乐扣给出的方法所采用的类型就是long.
思路二:
利用杨辉三角的定义,从上一层推到下一层。
class Solution {
public:
vector<int> getRow(int rowIndex) {
vector<int> result;
for(int i = 0; i <= rowIndex; ++i){
result.push_back(1);
for(int j = i - 1; j > 0; --j){
result[j] += result[j - 1];
}
}
return result;
}
};
作者:heromapwrd
链接:https://leetcode-cn.com/problems/pascals-triangle-ii/solution/c-8xing-dai-ma-jian-ji-yi-dong-by-heroma-2/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
Copy别人的算法,十分精妙,本质上就是利用上一层推到下一层,但是只是在O(n)的空间上去实现。