LeetCode-119. Pascal's Triangle II-Analysis and Code (Java)

LeetCode-119. Yang Hui Triangle II [Pascal's Triangle II]-Analysis and Code [Java]

1. Topic

Given a non-negative index k, where k ≤ 33, return the kth row of Yanghui triangle.
In the Yanghui triangle, each number is the sum of the numbers on its upper left and upper right.

Example:

输入: 3
输出: [1,3,3,1]

Advanced:
Can you optimize your algorithm to O(k) space complexity?

Source: LeetCode
Link: https://leetcode-cn.com/problems/pascals-triangle-ii The
copyright is owned by LeetCode . For commercial reprints, please contact the official authorization. For non-commercial reprints, please indicate the source.

Two, analysis and code

1. Direct calculation

(1) Thinking

According to the properties of Yanghui triangle, the m-th number in the nth row is C(n, m), combined with the combination number formula, the m-th number can be obtained as C(n, m) = C(n, m-1) * ( n-m + 1) / m.

(2) Code

class Solution {
    
    
    public List<Integer> getRow(int rowIndex) {
    
    //rowIndex从0计数
        List<Integer> row = new ArrayList<>();
        row.add(1);
        for (int i = 1; i <= rowIndex; i++)
            row.add((int) ((long) row.get(i - 1) * (rowIndex - i + 1) / i));
        return row;
    }
}

(3) Results

Execution time: 0 ms, beating 100.00% of users
in all Java submissions ; memory consumption: 36.5 MB, beating 14.94% of users in all Java submissions.

Three, other

Nothing.

Guess you like

Origin blog.csdn.net/zml66666/article/details/113839314