119. Pascal's Triangle II java solutions

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?

 1 public class Solution {
 2     public List<Integer> getRow(int rowIndex) {
 3         Integer[] num = new Integer[rowIndex+1];
 4         num[0] = 1;
 5         for(int i = 1; i < num.length; i++){
 6             num[i] = (int)((long)num[i-1]*(rowIndex-i+1)/i);//不加强制转换,乘积大于Integer.MAX_VALUE有溢出
 7         }
 8         return Arrays.asList(num);
 9     }
10 }
 1 public class Solution {
 2     public List<Integer> getRow(int rowIndex) {
 3         List<Integer> list = new ArrayList<Integer>();
 4         list.add(1);
 5         for(int i = 1; i < rowIndex + 1; i++){
 6             list.add((int)((long)list.get(i-1)*(rowIndex-i+1)/i));
 7         }
 8         return list;
 9     }
10 }

根据数学公式:

[C(k,0), C(k,1), ..., C(k, k-1), C(k, k)]

C[k,i] = C[k,i-1]*(k-i+1)/i

posted @ 2016-07-06 11:36  Miller1991  阅读(150)  评论(0编辑  收藏  举报