java递归算法的例子。

2025-04-24 12:08:21
推荐回答(3个)
回答1:

阶乘:

要求:给定一个数值,计算出它的阶乘值,例如5的阶乘为5*4*3*2*1

实现:

[html] view plaincopy

 // 利用递归实现一个数的阶乘值      private static BigDecimal getNum(BigDecimal inNum) {          if (inNum.compareTo(BigDecimal.ONE) == 0) {              return inNum;          }          return inNum.multiply(getNum(inNum.subtract(BigDecimal.ONE)));      }  

(2)Fibonacci数列:1,1,2,3,5,8,13……

要求:找出数列中指定index位置的数值

实现:

[html] view plaincopy

 // 利用递归实现了Fibonacci数列      private static int fab(int index) {          if (index == 1 || index == 2) {              return 1;          } else {              return fab(index - 1) + fab(index - 2);          }      }  

(3)汉诺塔

要求:汉诺塔挪动

实现:

[html] view plaincopy

  private static final String DISK_B = "diskB";       private static final String DISK_C = "diskC";       private static final String DISK_A = "diskA";       static String from=DISK_A;    static String to=DISK_C;    static String mid=DISK_B;      public static void main(String[] args) {        String input=JOptionPane.showInputDialog("please input the number of the disks you want me move.");        int num=Integer.parseInt(input);        move(num,from,mid,to);    }  

[html] view plaincopy

 // 利用递归实现汉诺塔      private static void move(int num, String from2, String mid2, String to2) {          if (num == 1) {              System.out.println("move disk 1 from " + from2 + " to " + to2);          } else {              move(num - 1, from2, to2, mid2);              System.out.println("move disk " + num + " from " + from2 + " to " + to2);              move(num - 1, mid2, from2, to2);          }      }  

(4)排列组合

要求:将输入的一个字符串中的所有元素进行排序并输出,例如:你给出的参数是"abc",

则程序会输出

abc

acb

bac

bca

cab

cba

实现:

[html] view plaincopy

  public static void permute(String str) {         char[] strArray = str.toCharArray();       permute(strArray, 0, strArray.length - 1);   }  

[html] view plaincopy

 // 利用递归实现,将输入的一个字符串中的所有元素进行排序并输出      public static void permute(char[] list, int low, int high) {          int i;          if (low == high) {              String cout = "";              for (i = 0; i <= high; i++) {                  cout += list[i];              }              System.out.println(cout);          } else {              for (i = low; i <= high; i++) {                  char temp = list[low];                  list[low] = list[i];                  list[i] = temp;                  permute(list, low + 1, high);                  temp = list[low];  

回答2:

十进制整数转二进制字符串的递归写法:

public String dtob(int n) {
if (n == 0 || n == 1) {
return Integer.toString(n);
} else {
return dtob(n / 2) + Integer.toString(n % 2);
}
}

回答3:

n!=n*(n-1)*(n-2)*......*2*1等同于n!=n*(n-1)! 其中n!与(n-1)!
相当于F(n)=n * F(n-1);所以F(n)方法如下:
public int F(int n){
if(n == 0){
return 1;
}
return n * F(n - 1);
}