java递归算法

1.汉诺塔问题
import javax.swing.JOptionPane;
  public class Hanoi {
  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);
  }
  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);
  }
  }
  }
2. 这是一个排列的例子,它所做的工作是将输入的一个字符串中的所有元素进行排序并输出,例如:你给出的参数是"abc" 则程序会输出:
  abc
  acb
  bac
  bca
  cab
  cba
  (1)算法的出口在于:low=high也就是现在给出的排列元素只有一个时。
  (2)算法的逼近过程:先确定排列的第一位元素,也就是循环中i所代表的元素,
  然后low+1开始减少排列元素,如此下去,直到low=high
  public static void permute(String str) {
  char[] strArray = str.toCharArray();
  permute(strArray, 0, strArray.length - 1);
  }
  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];
  list[low] = list[i];
  list[i] = temp;
  }
  }
  }
  3。这是一个组合的例子,与上述的例子相似,只是它所做的工作是,输出所给字符串中制定数目的元素的组合种类
  (1)程序出口在于n=1,此时只要输出目标数组的所有元素即可
  (2)逼近过程,当n>1 的时候,我们先取第一个元素放入目标数组中,然后n-1,如此下去,最后出来。
  import javax.swing.JOptionPane;
  public class Combination {
  /**
  * @param args
  */
  public static void main(String[] args) {
  String input = JOptionPane.showInputDialog("please input your String: ");
  String numString = JOptionPane.showInputDialog("please input the number of your Combination: ");
  int num = Integer.parseInt(numString);
  Combine(input, num);
  }
  private static void Combine(String input, int num) {
  char[] a = input.toCharArray();
  String b = "";
  Combine(a, num, b, 0, a.length);
  }
  private static void Combine(char[] a, int num, String b, int low, int high) {
  if (num == 0) {
  System.out.println(b);
  } else {
  for (int i = low; i < a.length; i++) {
  b += a[i];
  Combine(a, num - 1, b, i+1, a.length);
  b=b.substring(0, b.length()-1);
  }
  }
  }
  }

你可能感兴趣的:(java,C++,c,算法,swing)