119. Pascal's Triangle II(杨辉三角 II)

题目链接:https://leetcode.com/problems/pascals-triangle-ii/

思路:

一种比较直观的想法就是利用118题,把每一行依次求出来得到下一行,这样做速度有点慢。

另一种方法就是利用杨辉三角的性质:

每个数字等于上一行的左右两个数字之和。

可用此性质写出整个杨辉三角。即第n+1行的第i个数等于第n行的第i-1个数和第i个数之和,这也是组合数的性质之一。即 C(n+1,i)=C(n,i)+C(n,i-1)
比如, rowIndex = 6.
1st: 1=1
2nd: 6= 6 / 1
3rd: 15=6x5 / (1x2)
4th: 20=6x5x4 / (1x2x3)
5th: 15=6x5x4x3 / (1x2x3x4)
6th: 6 =6x5x4x3x2 / (1x2x3x4x5)
7th: 1 =6x5x4x3x2x1 / (1x2x3x4x5x6)

AC 0ms 100% Java:

class Solution {
    public List<Integer> getRow(int rowIndex) {
        List<Integer> ans=new ArrayList();
        if(rowIndex<0)
            return ans;
        ans.add(1);
        int low=1,high=rowIndex;
        long cur=1;
        for(int i=1;i<=rowIndex;i++,high--,low++){
            cur=cur*high/low;
            ans.add((int)cur);
        }
        return ans;
    }
}

猜你喜欢

转载自blog.csdn.net/God_Mood/article/details/89054758