关于Java Permutation程序的说明

时间:2012-08-26 11:08:07

标签: java permutation

这个问题对某些人来说似乎是基本的,但我一直在分析和剖析这段代码而没有成功,因为Robert Sedgewick的这个permutation程序如何在不使用system.out.print的情况下打印单词或字符的组合在方法perm1和perm2中。任何帮助或解释傻瓜非常感谢。提前谢谢。

这是链接下的代码:

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);
  }
}

1 个答案:

答案 0 :(得分:2)

就在那里:

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

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

相关问题