一、金字塔問題
題目如下:
輸出一個大寫字母組成的金字塔。,其中space表示金字塔底距離左邊的空白長度,x表示金字塔底的中心字母。
比如:space=0, x=’C’,則輸出:
A
ABA
ABCBA
再如:space=2,x=’E’, 則輸出:
A
ABA
ABCBA
ABCDCBA
ABCDEDCBA
public class 金字塔 {
public static void h(int space, char x){
int i;
if(x<'A' || x>'Z') return;
h(space+1,(char)(x-1));
for(i=0; i<space; i++) System.out.printf(" ");
for(i=0; i<x-'A'; i++) System.out.printf("%c",'A'+i);
for(i=0; i<=x-'A'; i++) System.out.printf("%c",(char)(x-i));
System.out.printf("n");
}
public static void main(String[] args) {
int space=0;//表示金字塔底距離左邊的空白長度
char x= 'F';//表示金字塔底的中心字母
h(space,x);
}
}
代碼運行結果如圖所示:
二、組合數問題
題目如下所示:
從4個人中選2個人參加活動,一共有6種選法。
從n個人中選m個人參加活動,一共有多少種選法?運用函數實現這個功能。
public class 組合數 {
// n 個元素中任取 m 個元素,有多少種取法
public static int f(int n, int m){
if(m>n) return 0;
if(m==0) return 1;
return f(n-1,m-1) + f(n-1,m);
}
public static void main(String[] args){
System.out.println(f(4,2));
}
}
代碼運行結果如圖所示:
文章出處:csdn博主--procedure源






