zoukankan      html  css  js  c++  java
  • leetcode-帕斯卡三角形

    帕斯卡三角形
    给定一个非负整数 numRows,生成杨辉三角的前 numRows 行。
    示例:
    输入: 5
    输出:
    [
    [1],
    [1,1],
    [1,2,1],
    [1,3,3,1],
    [1,4,6,4,1]
    ]
     
    思路:利用三角形性质 1*(n-1)*(n-2)/2 *(n-3)/3  * (n-4)/4    和杨辉三角形n行含有n个数字的数学性质。
    本题可以通过数学性质来获得求解。代码如下:   注意1*(n-1)*(n-2)/2 *(n-3)/3  * (n-4)/4中Int型数组导致运算结果为0的情况(如2/5=0,1/2=0)
    class Solution {
        public List<List<Integer>> generate(int numRows) {
            List<List<Integer>> res=new ArrayList<List<Integer>>();
            for(int i=1;i<=numRows;i++){
                List<Integer> list=new ArrayList();
                list.add(1);
                double temp=1;
                for(int j=1;j<i;j++){
                    temp=(temp*(i-j))/j;   //这个地方不能写成temp*=(i-j)/j  因为是Int型 (i-j)/j 会变成0.
                    list.add((int)temp);
                }
                
                res.add(list);
            }
            return res;
        }
    }

    另一种解法根据数组的性质,每一个数字都是上一组的前一个数与后一个数之和。

    class Solution {
        public List<List<Integer>> generate(int numRows) {
           List<List<Integer>> pascal = new ArrayList<List<Integer>>();
            ArrayList<Integer> row = new ArrayList<Integer>();
            for (int i = 0; i < numRows; i++) {
                row.add(0, 1);     //(0,1)中的0是索引,1是值。 每一组首先添加1进行运算
                for (int j = 1; j < row.size() - 1; j++)
                    row.set(j, row.get(j) + row.get(j + 1));    //上一组前两个数字的和
                pascal.add(new ArrayList<Integer>(row));
            }
            return pascal;
        }
    }
    class Solution {
        public List<List<Integer>> generate(int numRows) {
           List<List<Integer>> pascal = new ArrayList<List<Integer>>();
            ArrayList<Integer> row = new ArrayList<Integer>();
            for (int i = 0; i < numRows; i++) {
                row.add(0, 1);     //(0,1)中的0是索引,1是值。 每一组首先添加1进行运算
                for (int j = 1; j < row.size() - 1; j++)
                    row.set(j, row.get(j) + row.get(j + 1));    //上一组前两个数字的和
                pascal.add(new ArrayList<Integer>(row));
            }
            return pascal;
        }
    }
  • 相关阅读:
    (转)Linux端口nmap和netstat命令
    (转)Linux下增加交换分区的大小
    (转)centos7安装telnet服务
    (转)VmWare下安装CentOS7图文安装教程
    (转)Linux系统安装时分区的选择
    (转)硬盘分区备忘(主分区,扩展分区和逻辑分区)以及Linux硬盘分区工具parted 介绍
    (转).tar.gz文件和.rpm文件的区别
    (转)Linux(Centos)之安装Java JDK及注意事项
    ibatis中integer类型
    ibatis时间比较大小
  • 原文地址:https://www.cnblogs.com/patatoforsyj/p/9484442.html
Copyright © 2011-2022 走看看