• 杨辉三角


    题目如下:

    思路:三角形中每个数字等于它两肩上的数字相加。

    解法一:

     1 import java.util.Scanner;
     2 class test 
     3 {
     4     public static void main(String[] args) 
     5     {
     6         int i,h;
     7         int n;
     8         int[][] arr=new int[34][34];
     9         Scanner scanner=new Scanner(System.in);
    10         System.out.printf("输入n=");
    11         n=scanner.nextInt();
    12         
    13         for(h=0;h<n;h++)   //主要代码
    14         {
    15            for(i=0;i<=h;i++)
    16            {
    17               if(i==0 || i==n-1)
    18                  arr[h][i]=1;
    19               else
    20                  arr[h][i]=arr[h-1][i-1]+arr[h-1][i];
    21            }
    22         }
    23 
    24         for(i=0;i<n;i++)  //打印数组
    25         {
    26             for(h=0;h<=i;h++)
    27               System.out.printf("%-6d",arr[i][h]);
    28             System.out.printf("
    ");
    29         }
    30     }
    31 }

    解法二:

    使用递归,大同小异。

     1 import java.util.Scanner;
     2 class test 
     3 {
     4     static void yang(int arr[][],int h)
     5     {
     6        int i;
     7        if(h==0)
     8        {
     9            arr[0][0]=1;
    10            return;
    11        }
    12        yang(arr,h-1);
    13        for(i=0;i<=h;i++)
    14        {
    15           if(i==0 || i==h)
    16               arr[h][i]=1;
    17           else
    18               arr[h][i]=arr[h-1][i]+arr[h-1][i-1];
    19        }
    20        
    21     }
    22 
    23     public static void main(String[] args) 
    24     {
    25         int i,h;
    26         int n;
    27         int[][] arr=new int[34][34];
    28         Scanner scanner=new Scanner(System.in);
    29         System.out.printf("输入n=");
    30         n=scanner.nextInt();
    31 
    32         yang(arr,n);
    33         for(i=0;i<n;i++)  //打印数组
    34         {
    35             for(h=0;h<=i;h++)
    36               System.out.printf("%-6d",arr[i][h]);
    37             System.out.printf("
    ");
    38         }
    39     }
    40 }
  • 相关阅读:
    DES介绍
    jsp知识点
    浏览器地址传中文
    cookie
    null与“ ”的区别
    验证二叉查找树 · Validate Binary Search Tree
    二叉树中的最大路径和 · Binary Tree Maximum Path Sum
    最近公共祖先 · Lowest Common Ancestor
    平衡二叉树Balanced Binary Tree
    二叉树的最大/小/平衡 深度 depth of binary tree
  • 原文地址:https://www.cnblogs.com/ttpn2981916/p/6416177.html
Copyright © 2020-2023  润新知