疯狂java


您现在的位置: 疯狂软件 >> 新闻资讯 >> 正文

输出全排列


 

     本文将给出一个使用回溯法实现全排列的程序。

  Java代码

  public class Permutations {

  public void permute(String value, int startIndex, int endIndex) {

  if (startIndex == endIndex) {

  System.out.printf("%s ", value);

  } else {

  for (int currIndex = startIndex; currIndex <= endIndex; currIndex++) {

  value = swap(value, startIndex, currIndex);

  permute(value, startIndex + 1, endIndex);

  /** 回溯 */

  value = swap(value, startIndex, currIndex);

  }

  }

  }

  private String swap(String value, int idxOne, int idxTwo) {

  char[] charArray = value.toCharArray();

  char temp = value.charAt(idxOne);

  charArray[idxOne] = charArray[idxTwo];

  charArray[idxTwo] = temp;

  return new String(charArray);

  }

  }

  测试程序如下:

  Java代码

  public class Main {

  public static void main(String[] args) {

  String value = "ABCD";

  new Permutations().permute(value, 0, value.length()-1);

  }

  }

  运行结果:

  ABCD

  ABDC

  ACBD

  ACDB

  ADCB

  ADBC

  BACD

  BADC

  BCAD

  BCDA

  BDCA

  BDAC

  CBAD

  CBDA

  CABD

  CADB

  CDAB

  CDBA

  DBCA

  DBAC

  DCBA

  DCAB

  DACB

  DABC