leetcode | Pascal's Triangle II

Given an index k, return the kth row of the Pascal's triangle.

For example, given k = 3,
Return [1,3,3,1].

Note:
Could you optimize your algorithm to use only O(k) extra space?

第n行的第r个元素的表达式是nCr, 就是排列组合,有一个公式  nCr = (n-r+1)/r  *  nC(r-1);

public class Solution {
    public List<Integer> getRow(int rowIndex) {
            List<Integer> row = new ArrayList<>();
            int n = rowIndex+1;
            for(int i=0;i<n;i++)
            {
                row.add((int)C(rowIndex,i));
            }
            return row;
    }        
        
        

        public long C(int n,int r)
        {
            long re = 1;
            for(int i=1;i<=r;i++)
            {
                re = re*(n-i+1)/i;
            }
            return re;
        }
}


你可能感兴趣的:(LeetCode)