题目:Given an index k, return the kth row of the Pascal's triangle.
For example, given k =
3,
Return [1,3,3,1]
.
思路:递推
思路很明确,一层一层递推,并且只需要设立一个数组,本题不难。只需要注意一个解题公式即可
代码:
class Solution1 {
public://for more information,please email:j.z.feng@foxmail.com
vector<int> getRow(int rowIndex) {
vector<int> result(1,1);
if(rowIndex==0){
return result;
}
for(int i=1;i<=rowIndex;i++){
vector<int>temp=result;
for(int j=1;j<=i-1;j++){
result[j]=temp[j]+temp[j-1];
}
result.push_back(1);
temp.clear();
}
return result;
}
};
class Solution2 {
//此版本更加简洁
public:<pre name="code" class="cpp">//for more information,please email:j.z.feng@foxmail.com
vector<int> getRow(int rowIndex) { vector<int> result(rowIndex+1,1); if(rowIndex<=1){ return result; } for(int i=2;i<=rowIndex;i++){ for(int j=i-1;j>=1;j--){ result[j]=result[j]+result[j-1]; } } return result; }};