vector<int> getRow(int rowIndex) { int *arr = new int[rowIndex+2]; int *arr1 = new int[rowIndex+2]; std::vector<int> v; if (rowIndex == 0) { v.push_back(1); return v; } arr[1] = 1; arr[2] = 1; int *src, *des; for (int i = 2; i <= rowIndex; ++i) { if ((i & 1)==0){ src = arr; des = arr1; } else{ src = arr1; des = arr; } des[1] = 1; des[2] = src[2] + 1; //cout << des[2] << endl; for (int j = 3; j < i+1; ++j) { des[j] = src[j - 1] + src[j]; } des[i+1] = 1; } if (rowIndex & 1) src = arr; else src = arr1; for (int i = 1; i <= rowIndex+1; ++i) { v.push_back(src[i]); } delete[] arr; delete[] arr1; return v; }
最初的想法,通过两个一维数组迭代,因为当前行的值需要上一行的值,看完别人写的发现自己逗B了,其实可以发现,pascal三角形每行相比前行多一个数,那么可以通过一个数组来做,先将最后一个数右移一位,然后按公式算就行,代码如下
vector<int> getRow(int rowIndex) { std::vector<int> v; int i,j; int *a=new int[rowIndex+1]; for (i = 0; i <= rowIndex; ++i) { a[0]=1; a[i]=1; for (j=i-1;j>0;--j) { a[j]=a[j-1]+a[j]; } } for (i = 0; i <= rowIndex; ++i) { v.push_back(a[i]); } delete[] a; return v; }