遞推遞歸組合數,漢諾塔,回文數問題(java)
遞推遞歸組合數:
1 思路:用函數求得n!,調用函數計算結果流程圖
2 .1流程圖
3 .1源代碼:
import java.util.Scanner;
public class N {
public static void main(String [] args){
int n,k;
int S;
System.out.println("請輸入C(n,k)中n和k的值:");
Scanner num = new Scanner(System.in);
n=num.nextInt();
k=num.nextInt();
S=fun(n)/(fun(k)*fun(n-k));
System.out
}
static int fun(int a)
{
int m=1;
for (int b=1;b<a;b++){
m=m*(b+1);
}
return m;
}
}
4.1 結果
2.2 流程圖
3.2 源代碼:
import java.util.Scanner;
public class Fact {
static int fun(int a){
if(a==0||a==1){
return a;
}
else {
return a*fun(a-1);
}
}
public static void main(String[]args){
int n,k;
System.out.println("請輸入n和k");
Scanner num = new Scanner(System.in);
n=num.nextInt();
k=num.nextInt();
int C;
C=fun(n)/(fun(k)*fun(n-k));
System.out.println("result:"+C);
}
}
4.2 結果:
2.3 流程圖:
3.3 源代碼:
import java.util.Scanner;
public class Yanghui {
public static void main(String []args){
int n = 0,k;
int b[][];
System.out.println("請輸入n的值:");
Scanner num = new Scanner(System.in);
n=num.nextInt();
k=num.nextInt();
b = new int[n][];
for (int i=1;i<=n;i++){
b[i-1] = new int[i];
}
for(int j=0;j<n;j++){
for(int z=0;z<=j;z++){
if(j==0||z==0||z==j){
b[j][z]=1;
continue;
}
else{
b[j][z] = b[j-1][z-1]+b[j-1][z];
}
}
}
for(int x=0;x<n;x++){
for(int y=0;y<=x;y++){
System.out.print(b[x][y]+" ");
}
System.out.println(" ");
}
int S;
S=b[n-1][k-2]+b[n-1][k-1];
System.out.println("和是:"+S);
}
}
4.3 結果:
漢諾塔:(百度的)
流程圖:
源代碼:
import java.util.Scanner;
public class Hannuota {
public static void main(String[] args)
{
Hannuota h=new Hannuota();
h.go();
}
public void go()
{
System.out.println("請輸入盤子的個數n:");
@SuppressWarnings("resource")
Scanner scanner=new Scanner(System.in);
int n=scanner.nextInt();
if(n>=0)//判斷n是否符合要求
{
System.out.println("移動"+n+"個盤子的步驟為:");
hanoi(n,‘A‘,‘B‘,‘C‘);
}
else System.out.println("輸入的數不符合要求");
}
public void hanoi(int m,char one,char two,char three)
{
if(m==1)
move(one,three);
else
{
hanoi(m-1,one,three,two);//第一步將A上n-1個盤子借助C移到B上
move(one,three);//第二步將A上一個盤子移到C上
hanoi(m-1,two,one,three);//第三步將B上n-1個盤子借助A移到C上
}
}
public void move(char x,char y)
{
System.out.println(x+"->"+y);
}
}
3 結果:
回文:
1 設計思想:
定義字符串,獲取長度,利用遞歸函數判斷兩頭是否相等。
2 流程圖:
3源代碼:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Huiwen {
public static void main(String[] args)
{
Huiwen h=new Huiwen();
try {
h.go();
} catch (IOException e) {
e.printStackTrace();
}
}
public void go() throws IOException
{
String input=null;
System.out.println("輸入字符串:");
BufferedReader is=new BufferedReader(new InputStreamReader(System.in));
input=is.readLine();
if(!input.isEmpty())
{
int [] array=new int[input.length()];
for(int i=0;i<input.length();i++)
{
array[i]=input.charAt(i);
}
System.out.println("是回文數?"+ifHuiWen(array,0));
}
else System.out.println("輸入的數不符合要求");
}
public boolean ifHuiWen(int[] a,int l)
{
if(l==a.length/2)
return true;
if(a[l]==a[a.length-l-1])
return ifHuiWen(a,l+1);
else return false;
}
}
4結果:
遞推遞歸組合數,漢諾塔,回文數問題(java)