首页 > 编程语言 > 详细

119. Pascal's Triangle II java solutions

时间:2016-07-06 11:39:25      阅读:152      评论:0      收藏:0      [点我收藏+]

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

119. Pascal's Triangle II java solutions

原文:http://www.cnblogs.com/guoguolan/p/5646375.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!