2016-06-22 66 views
-1

我已經編寫了一個使用嵌套循環的遞歸方法來打印給定字符串的所有排列。它會打印所有排列,但不止一次有人能夠找出問題以及在條件下要更改的內容解決這個問題?使用嵌套循環獲取字符串的排列

public static String swap(String x,int a,int b){ 
    char list[]=x.toCharArray(); 
    char tmp=x.charAt(a); 
    list[a]=list[b]; 
    list[b]=tmp; 
    return new String(list); 
} 
public static void perm(String x,String base){ 
    if(base.length()==3) 
     System.out.println(base); 
    for(int i=0;i<x.length();i++) 
     for(int j=i;j<x.length();j++){ 
      String tmp=swap(x,i,j); 
      perm(tmp.substring(1),base+tmp.charAt(0)); 
     } 
} 

示例: 輸入:「abc」。 輸出: ABC ACB ABC BAC BCA BAC CBA 駕駛室 CBA ABC ACB ABC ACB ABC ACB ABC ACB ABC。

+0

您能否包括輸入,預期輸出和實際輸出。 – bhspencer

+0

@bhspencer補充說, –

+0

其中的perm方法的代碼的其餘部分? –

回答

0

下面是我根據您的代碼所做的修改版本。

public static void main(String[] args) { 
    String str = "abc"; 
    char[] chars = str.toCharArray(); 
    perm(chars, 0); 
} 

public static void swap(char[] x, int a, int b) { 
    char tmp = x[a]; 
    x[a] = x[b]; 
    x[b] = tmp; 
} 

public static void perm(char[] x, int idx) { 
    if (idx == x.length) { 
     for (int i = 0; i < x.length; i++) 
      System.out.print(x[i]); 
     System.out.println(); 
    } 

    for (int i = idx; i < x.length; i++) { 
     swap(x, idx, i); 
     perm(x, idx + 1); 
     swap(x, idx, i); 
    } 
}