java - Java排列程序详解

标签 java permutation

这个问题对某些人来说可能看起来很基本,但我一直在分析和剖析这段代码,但没有成功地了解 permutation 是如何实现的。 Robert Sedgewick 的程序打印单词或字符的组合,而无需在方法 perm1 和 perm2 中使用 system.out.print。非常感谢对傻瓜的任何帮助或解释。预先感谢您。

这是链接下的代码:

public class Permutations {
  // print N! permutation of the characters of the string s (in order)
  public  static void perm1(String s) { perm1("", s); }
  private static void perm1(String prefix, String s) {
      int N = s.length();
      if (N == 0) System.out.println(prefix);
      else {
          for (int i = 0; i < N; i++)
             perm1(prefix + s.charAt(i), s.substring(0, i) + s.substring(i+1, N));
      }
  }
  // print N! permutation of the elements of array a (not in order)
  public static void perm2(String s) {
     int N = s.length();
     char[] a = new char[N];
     for (int i = 0; i < N; i++)
         a[i] = s.charAt(i);
     perm2(a, N);
  }

  private static void perm2(char[] a, int n) {
      if (n == 1) {
          System.out.println(a);
          return;
      }
      for (int i = 0; i < n; i++) {
          swap(a, i, n-1);
          perm2(a, n-1);
          swap(a, i, n-1);
      }
  }  

  // swap the characters at indices i and j
  private static void swap(char[] a, int i, int j) {
      char c;
      c = a[i]; a[i] = a[j]; a[j] = c;
  }

  public static void main(String[] args) {
     int N = Integer.parseInt(args[0]);
     String alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
     String elements = alphabet.substring(0, N);
     perm1(elements);
     System.out.println();
     perm2(elements);
  }
}

最佳答案

就在那里:

if (N == 0) System.out.println(prefix);

System.out.printSystem.out.println 基本相同,只是后者在文本后打印换行符。

关于java - Java排列程序详解,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12129599/

相关文章:

php - 创建较大集合的固定长度非重复排列

java - 错误 : No enclosing instance of type Main is accessible. 必须使用 Main 类型的封闭实例来限定分配(例如 x.new A() wh

java - Java中如何解决字节填充问题?

java - Regex 类在 GWT 的服务器端不起作用

flash - MXMLC 和 64 位 JRE

c - C中的矩阵问题

java - Java中静态和非静态方法的重载和重写

python - 生成所有可能的交替数字和字母序列

java - 如何在Java中生成通过排列2个位置获得的组合

线分割排列的算法