Leetcode 119 杨辉三角

 

  C:

int *level(int *pre, int rowIndex, int currLevel, int *returnSize)
{
    int currSize = *returnSize + 1;
    int *currList = (int *)malloc(sizeof(int) * currSize);
    memset(currList, 0, sizeof(int)*currSize);

  currList[0] = 1;
    currList[currSize - 1] = 1;
    for (int i = 1; i < currSize-1; i++)
        currList[i] = pre[i - 1] + pre[i];
    free(pre);
    *returnSize = currSize;
    if (rowIndex == currLevel)
        return currList;
    else
        return level(currList, rowIndex, currLevel + 1, returnSize);
}

/**
 * Note: The returned array must be malloced, assume caller calls free().
 */
int *getRow(int rowIndex, int *returnSize)
{
    *returnSize = 1;
    int *first = (int *)malloc(sizeof(int));
    first[0] = 1;
    if (rowIndex == 0)
        return first;
    else
        return level(first, rowIndex, 1, returnSize);
}

  JAVA:

    public List<Integer> getRow(int rowIndex) {
        List<Integer> first = new ArrayList<Integer>(1);
        first.add(1);
        if (rowIndex == 0) return first;
        return level(first, rowIndex, 1);
    }

    private final List<Integer> level(List<Integer> pre, int targetLevel, int currLevel) {
        int currSize = pre.size() + 1;
        List<Integer> currList = new ArrayList<Integer>(currSize);
        currList.add(1);
        for (int i = 1; i < currSize - 1; i++) {
            currList.add(i, pre.get(i - 1) + pre.get(i));
        }
        currList.add(currSize - 1, 1);
        if (currLevel == targetLevel) return currList;
        return level(currList, targetLevel, currLevel + 1);
    }

  JS:

/**
 * @param {number} rowIndex
 * @return {number[]}
 */
var getRow = function (rowIndex) {
    let first = [1];
    if (rowIndex == 0) return first;
    return level(first, rowIndex, 1);
};

var level = function (pre, targetLevel, currLevel) {
    let currList = [];
    currList.push(1);
    for (let i = 1; i < pre.length; i++) {
        currList.push(pre[i - 1] + pre[i]);
    }
    currList.push(1);
    if (targetLevel == currLevel) return currList;
    else return level(currList, targetLevel, currLevel + 1);
}

 

posted @ 2022-02-21 10:08  牛有肉  阅读(19)  评论(0编辑  收藏  举报