标签:style blog http io color ar for sp div
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 }
提交以后,发现错误:
这已经是我将辅助函数getNumber中的result设为long型以后的结果了。
Solution 2:
getNumber
[Leetcode] Pascal's Triangle II
标签:style blog http io color ar for sp div
原文地址:http://www.cnblogs.com/Phoebe815/p/4068759.html