码迷,mamicode.com
首页 > 其他好文 > 详细

杨辉三角

时间:2017-02-19 18:03:19      阅读:164      评论:0      收藏:0      [点我收藏+]

标签:span   bsp   str   main   img   for   print   杨辉三角   ++   

题目如下:

技术分享

 

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

解法一:

 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("\n");
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("\n");
38         }
39     }
40 }

 

杨辉三角

标签:span   bsp   str   main   img   for   print   杨辉三角   ++   

原文地址:http://www.cnblogs.com/ttpn2981916/p/6416177.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!