每日一贴,今天的内容关键字为输出空格
/* 杨辉三角 (a+b)的n次幂的展开式中各项的系数很有法则, 对于n=2,3,4分时别是:1 2 1, 1 3 3 1,1 4 6 4 1。这些系数构成了名著的杨辉三角形: 1 1 1 1 2 1 1 3 3 1 1 4 6 4 1 1 5 10 10 5 1 列下的程序给出了盘算第m层的第n个系数的盘算方法,试完善之(m,n都从0算起)。 */ public class 杨辉三角 { public static int f(int m, int n) { if (m == 0) return 1; if (n == 0 || n == m) return 1; return f(m-1,n-1) + f(m-1,n); } public static void main(String[] args) { System.out.print(f(5,2)); } }
行运结果:
10
展扩:杨辉三角按金字塔式格输出
import java.util.Scanner; public class 杨辉三角2 { // 失掉最大数的长度 public static int getMaxLen(int[] n){ int sum = 0; for(int i=0;i<=n.length/2;i++){ if(n[i]>sum){ sum = n[i]; } } return (""+sum).length(); } // 初始化填充杨辉三角 public static void init(int[][] m) { m[0] = new int[]{1}; // 初始第一行 for(int i=1;i<m.length;i++){ m[i] = new int[i+1]; for(int j=0;j<=i;j++){ if(j==0||j==i){ m[i][j] = 1; }else{ m[i][j] = m[i-1][j-1] + m[i-1][j]; } } } } // 输出空格 public static void printSp(int n){ for(int i=0;i<n;i++){ System.out.print(" "); } } // 示显杨辉三角 public static void show(int[][] m) { int len = getMaxLen(m[m.length-1]); // 失掉最大数的长度+1个空格 if(len%2==0){ // 上一行下和对齐 len += 2; // 偶数加2 }else{ len += 1; // 奇数加1 } for(int i=0;i<m.length;i++){ // 输出 printSp((m.length-i)*len/2); // 输出(每行前)的多少空格 for(int j=0;j<=i;j++){ System.out.print(m[i][j]); printSp(len-(m[i][j]+"").length()); // 输出(数字间)的多少空格 } System.out.println(); } } public static void main(String[] args){ Scanner scan = new Scanner(System.in); System.out.println("输入行数(数整n):"); int n = scan.nextInt(); if(n<=0) return ; int[][] m = new int[n][]; init(m); // 初始化填充杨辉三角 show(m); // 示显杨辉三角 } }
行运结果:
输入行数(数整n): 12 1 1 1 1 2 1 1 3 3 1 1 4 6 4 1 1 5 10 10 5 1 1 6 15 20 15 6 1 1 7 21 35 35 21 7 1 1 8 28 56 70 56 28 8 1 1 9 36 84 126 126 84 36 9 1 1 10 45 120 210 252 210 120 45 10 1 1 11 55 165 330 462 462 330 165 55 11 1
文章结束给大家分享下程序员的一些笑话语录: 腾讯的动作好快,2010年3月5日19时28分58秒,QQ同时在线人数1亿!刚刚看到编辑发布的文章,相差才2分钟,然后连专题页面都做出来了,他们早就预料到了吧?(其实,每人赠送10Q币,轻轻松松上两亿!)