zoukankan      html  css  js  c++  java
  • leetCode-Pascal's Triangle II

    Description:
    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?

    My Solution:

    class Solution {
        public List<Integer> getRow(int rowIndex) {
            List list = new ArrayList();
            for(int i = 0;i <= rowIndex;i++){
                List<Integer> line = new ArrayList<Integer>();
                for(int j = 0;j <= i;j++){
                    if(j == 0 || j== i){
                        line.add(1);
                    }else{
                        List<Integer> temp = (ArrayList<Integer>)list.get(list.size() - 1);
                        line.add(temp.get(j - 1) + temp.get(j));
                    }
                }
                list.add(line);
            }
            return (ArrayList<Integer>)list.get(list.size() - 1);
        }
    }

    Better Solution:

    class Solution {
        public List<Integer> getRow(int rowIndex) {
            rowIndex+=1;
            int[][] res=new int[rowIndex][];
            List<Integer> RES=new ArrayList<>();
            for(int i=0;i<rowIndex;i++){
                res[i]=new int[i+1];
                for(int j=0;j<i+1;j++){
                    if(j==0||j==i)res[i][j]=1;
                    else res[i][j]=res[i-1][j-1]+res[i-1][j];
                    if(i==rowIndex-1)RES.add(res[i][j]);
                }
            }
            return RES;
        }
    }

    Best Solution:

    class Solution {
        public List<Integer> getRow(int rowIndex) {
            List<Integer> result=new ArrayList<Integer>();
            for(int k=0,value=1;k<=rowIndex;k++){
                result.add(value);
                //核心
                value=(int)((long)value*(rowIndex-k)/(k+1));
            }
            return result;
        }
    }
  • 相关阅读:
    sql面试题
    C#基础(1)
    Java中的冒泡排序(减少比较次数)
    Java中面向对象的分拣存储
    Java中分拣存储的demo
    XML序列化
    C#读取csv文件使用字符串拼接成XML
    Java中HashMap(泛型嵌套)的遍历
    Java 中List 集合索引遍历与迭代器遍历
    java 中的try catch在文件相关操作的使用
  • 原文地址:https://www.cnblogs.com/kevincong/p/7900348.html
Copyright © 2011-2022 走看看