2016-03-20 5 views
0

Ich lerne vor kurzem den Algorithmus, heute bin ich gespannt mit einem Problem: Warum die Swap-Funktion zweimal in der String-Permutation rekursiv ausgeführt werden? Wie kann ich das verstehen? Könnten Sie mir helfen?Warum die String-Permutation zweimal im Programm tauschen?

public class Permutation { 
    public static void swap(char[] str, int i, int j) { 
     char temp = str[i]; 
     str[i] = str[j]; 
     str[j] = temp; 
    } 

    public static void permutation(char[] str) { 
     if (str==null)return; 
     permutation(str,0); 
    } 

    private static void permutation(char[] str, int begin) { 
     if (begin == str.length) { 
      System.out.println(Arrays.toString(str)); 
     } else { 
      for (int i = begin;i<str.length;i++) { 
       swap(str, begin, i); 
       permutation(str, begin + 1); 
       swap(str, begin, i); 
      } 
     } 
    } 

    public static void main(String[] args) { 
     char[] a = {'a', 'b', 'c', 'd'}; 
     permutation(a); 
    } 
} 

Antwort

2
for (int i = begin;i<str.length;i++) { 
       swap(str, begin, i); 
       permutation(str, begin + 1); 
       swap(str, begin, i); 

Dieses Codefragment ruft die nächste Rekursionstiefe mit String geändert, dann wieder String zurück

+0

Warum erste Iteration mit sich selbst Swap-Element? Warum fangen wir nicht mit "i = begin + 1" an? –

Verwandte Themen