zoukankan      html  css  js  c++  java
  • [LeetCode] Pascal's Triangle II

    Question:

    Given an index k, return the kth row of the Pascal's triangle.

      For example, given k = 3,
      Return [1,3,3,1].

    1、题型分类:

    2、思路:直接使用公式,第n行  第0个数是1,从第i个数开始一次是 N[i-1]*(n-i)/i  ,(n是从0开始)。需要注意的是这里会出现直接采用前面的公式会出现超过Integer.Max_Value的情况,需要先除再乘  除之前需乘上1.0,防止两个整数相除结果取整的情况。

    3、时间复杂度:

    4、代码:

        public List<Integer> getRow(int rowIndex) {
            if(rowIndex<0) return null;
            rowIndex+=1;
            List<Integer> list=new ArrayList<Integer>();
            for(int i=0;i<rowIndex;i++)
            {
                if(i==0) {list.add(1);continue;}
                if(Integer.MAX_VALUE/list.get(i-1).intValue()<rowIndex-i)
                    list.add((int)(list.get(i-1).intValue()*1.0/i*(rowIndex-i)));
                else 
                    list.add(list.get(i-1).intValue()*(rowIndex-i)/i);
            }
            return list;
        }

    5、优化:

      网上很多朋友的办法,外层循环是从第一层开始利用规则往下计算,直到第N层,内层循环是从第二个数到倒数第二个数,其中利用一个temp代表被取代的数。

    public class Solution {
        public List<Integer> getRow(int rowIndex) {
            if(rowIndex<0) return null;
            rowIndex+=1;
            List<Integer> list=new ArrayList<Integer>();
            list.add(1);
            for(int i=1;i<rowIndex;i++)
            {
                int temp=1;
                for(int j=1;j<i;j++)
                {
                    int tempInner=list.get(j);
                    list.set(j, temp+tempInner);
                    temp=tempInner;
                }
                list.add(1);
            }
            return list;
        }
    }

    6、扩展:

  • 相关阅读:
    springboot整合Swagger2
    FastJson会把哪些字符串解析为null
    BitMap再再体验之布隆过滤器
    如何利用windows自带的画图工具拼接图片
    BitMap再体验之排序
    BitMap 初体验
    Chrome 隐藏最常访问的网站
    idea同一个项目不同端口启动
    ubuntu16搭建harbor镜像库
    virtualbox硬盘扩容
  • 原文地址:https://www.cnblogs.com/maydow/p/4644861.html
Copyright © 2011-2022 走看看