递推递归组合数,汉诺塔,回文数问题(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.println("C("+n+k+")结果是:"+S); } 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结果: