Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

119. Pascal's Triangle II #295

Open
Tcdian opened this issue Aug 12, 2020 · 1 comment
Open

119. Pascal's Triangle II #295

Tcdian opened this issue Aug 12, 2020 · 1 comment
Labels

Comments

@Tcdian
Copy link
Owner

Tcdian commented Aug 12, 2020

119. Pascal's Triangle II

给定一个非负索引 k,其中 k ≤ 33,返回杨辉三角的第 k 行。

在杨辉三角中,每个数是它左上方和右上方的数的和

Example

Input: 3
Output: [1,3,3,1]

Follow up

  • 你可以优化你的算法到 O(k) 空间复杂度吗?
@Tcdian Tcdian added the Array label Aug 12, 2020
@Tcdian
Copy link
Owner Author

Tcdian commented Aug 12, 2020

Solution

  • JavaScript Solution
/**
 * @param {number} rowIndex
 * @return {number[]}
 */
var getRow = function(rowIndex) {
    const reuslt = new Array(rowIndex + 1);
    for (let i = 0; i <= rowIndex; i++) {
        for (let j = i; j >= 0; j--) {
            if (j === i || j === 0) {
                reuslt[j] = 1;
            } else {
                reuslt[j] = reuslt[j] + reuslt[j - 1];
            }
        }
    }
    return reuslt;
};
  • TypeScript Solution
function getRow(rowIndex: number): number[] {
    const reuslt: number[] = new Array(rowIndex + 1);
    for (let i = 0; i <= rowIndex; i++) {
        for (let j = i; j >= 0; j--) {
            if (j === i || j === 0) {
                reuslt[j] = 1;
            } else {
                reuslt[j] = reuslt[j] + reuslt[j - 1];
            }
        }
    }
    return reuslt;
};

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant