首页 > 其他 > 详细

[Leetcode] Pascal's Triangle II

时间:2014-11-02 12:10:48      阅读:203      评论: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?

 

Solution 1: 直接利用数学公式来求解。

 1 public class Solution {
 2     public List<Integer> getRow(int rowIndex) {
 3         List<Integer> result = new ArrayList<Integer>();
 4         if (rowIndex < 0)
 5             return result;
 6         
 7         for(int i=0;i<rowIndex;++i){
 8             int a=getNumber(rowIndex,i);    
 9             result.add(a);
10         }
11         result.add(1);
12         return result;
13     }
14 
15     private int getNumber(int rowIndex, int i) {
16         // TODO Auto-generated method stub
17         long result=1l;
18         for(int j=0;j<i;++j){
19             result*=rowIndex--;
20         }
21         
22         for(int j=i;j>0;--j){
23             result/=j;
24         }
25         return (int) result;
26     }
27 }

提交以后,发现错误:

bubuko.com,布布扣

这已经是我将辅助函数getNumber中的result设为long型以后的结果了。 

 

Solution 2: 

getNumber

[Leetcode] Pascal's Triangle II

原文:http://www.cnblogs.com/Phoebe815/p/4068759.html

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