2016-03-20 43 views
0

我最近學習的算法,今天我緊張着一個問題:爲什麼交換函數在字符串排列遞歸方式下運行兩次?我怎麼理解它?你能幫助我嗎?爲什麼字符串排列在程序中交換兩次?

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

回答

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

這段代碼調用與下一個遞歸級別修改字符串,然後恢復字符串返回

+0

爲什麼與自己第一次迭代的交換元素?爲什麼我們不以'i = begin + 1'開頭 –