title: Permutations of a string with no duplicates
body: <p>I read solutions to the problem of generating all the permutations of a string (<a href="http://introcs.cs.princeton.edu/java/23recursion/Permutations.java.html" rel="nofollow">solution</a>). </p>
  
  <p>Can anyone explain how perm2 is different from perm1? (I feel the only difference is that perm1 tries to put each element in the first position while perm2 in the last one)</p>
  
  <pre><code>// 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 &lt; 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 &lt; 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 &lt; n; i++) {
              swap(a, i, n-1);
              perm2(a, n-1);
              swap(a, i, n-1);
          }
      }
  </code></pre>
  
  <p>Also, if some letters are the same in the string, then some permutations will be the same? The only way I can think of to prevent this is to save the result in a hashset so as to keep only one instance of a permutation. Is there a better solution?</p>