zoukankan      html  css  js  c++  java
  • 杨辉三角问题(二维数组解决较为简便)

    由杨辉三角的定义可知:某一项等于上面的一项与左上角的那项的和,于是可以想到用二维数组,java中的二维数组其实就是一维数组的一维数组,所以第二维的数组长度可以任意指定,用法比较灵活。
     1  public class TestSysin {
     2      public static void main(String[] args) {
     3          int triangle[][]=new int[10][];//创建二维数组
     4         for (int i = 0; i < triangle.length; i++) {
     5                triangle[i]=new int[i+1];//初始化第二层数组的大小,可以对比一下一维数组的初始化,int a[]; a=new int[6];
     6              for (int j = 0; j <=i;j++) {
     7                 if (i==0||j==0||i==j) {//两侧的数组都赋值为1
     8                    triangle[i][j]=1;
     9                   }else{
    10                      triangle[i][j]=triangle[i-1][j-1]+triangle[i-1][j];
    11                   }
    12                  System.out.print(triangle[i][j]+"    ");
    13             }
    14               System.out.println();
    15         }
    16          
    17       }
    18  }

     

     
  • 相关阅读:
    表达式for loop
    用户输入
    字符编码
    变量字符编码
    Python安装
    Python 2 or 3?
    Python解释器
    2017中国大学生程序设计竞赛
    Educational Round 27
    Round #429 (Div.2)
  • 原文地址:https://www.cnblogs.com/imqsl/p/6151529.html
Copyright © 2011-2022 走看看