zoukankan      html  css  js  c++  java
  • [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?

    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
  • 相关阅读:
    day09
    day08
    day05
    day04
    day03
    day02
    LogCat查看Android运行日志
    ADT+SDK,Android开发环境搭建问题
    第二次冲刺周期第十天
    第二次冲刺周期第九天
  • 原文地址:https://www.cnblogs.com/Phoebe815/p/4068759.html
Copyright © 2011-2022 走看看