Pascal's Triangle II

来源:互联网 发布:淘宝宝贝主图怎么修改 编辑:程序博客网 时间:2024/05/29 02:56

比一式简单,至少不用返回多维数组。

不过不知为何再翻回来的时候OJ的函数申明貌似跟AC的不一样了,但反正当时是AC了的。

如下:

struct IntArray {  int* elements;  int size;};struct IntArray* getRow(int rowIndex) {    if (rowIndex < 0)        return NULL;    struct IntArray *result = (struct IntArray *)malloc(sizeof(struct IntArray));    result->elements = (int *)malloc(sizeof(int) * (rowIndex + 1));    result->elements[0] = 1;    result->size = rowIndex + 1;    if (rowIndex == 0)        return result;    int lastleft = 0, last = 0;    for (int i = 1; i <= rowIndex; i++) {        for (int j = 0; j <= i; j++) {            if (j - 1 < 0)                lastleft = 0;            else                lastleft = last;            if (j == i) {                result->elements[j] = 1;                continue;            }            last = result->elements[j];            result->elements[j] = lastleft + last;        }    }    return result;}

解答的更简单:

class Solution {public:vector<int> getRow(int rowIndex) {vector<int> array;for (int i = 0; i <= rowIndex; i++) {for (int j = i - 1; j > 0; j--){array[j] = array[j - 1] + array[j];}array.push_back(1);}return array;}};


0 0