2012-08-30 33 views
6

我是10年級的高中學生,嘗試解決Java中的數據結構和算法一書中的一些問題。Java中的字符串排列(非遞歸)

其中一個問題是打印一個字符串的所有排列。

class C14 
{ 
public static void main(char a[]) 
{ 
    // char[] a = {'c','a','r','b','o','n'}; 
    int c=0,w=0; 
    for(int q = 0;q<a.length;q++) 
    { 
     for(int i=0;i<a.length;i++) 
     { 
      for(int j=1;j<a.length;j++) 
      { 
       for(int k=1;k<a.length-1;k++) 
       { 
        for(int z=0;z<a.length;z++) 
        { 
         System.out.print(a[z]); 
         c++; 
        } 
        w++; 
        System.out.println(); 
        char p=a[k+1]; 
        a[k+1]=a[k]; 
        a[k]=p; 
       } 
       System.out.println(); 
      } 
      System.out.println(); 
      char x=a[0]; 
      a[0]=a[1]; 
      a[1]=x; 
     } 
     } 
    System.out.println(" Character count = " + c); 
    System.out.println(" Word count = " + w); 
    } 
} 

這是我的嘗試。這本書要求我爲角色'c','a','r','b','o','n'做這個。 我的解決方案就是這樣做的,但是當我嘗試使用3或4個字母的單詞時,它會給我重複。如果我刪除最外面的循環並嘗試打印它,它適用於3個和4個字母的單詞,但不適用於5個以上的字母單詞。

我很樂意澄清我的理由,我知道這不是最有效率的,但要記住我只是在10年級這一事實,這是我首先想到的。

有人可以幫助我,或至少暗示有什麼不對嗎? 請不要建議遞歸解決方案,因爲我想先迭代地完成它。感謝, Sumit。

+0

這是怎麼回事 - http://stackoverflow.com/questions/11915026/permutations-of-a-string-using-iteration? –

+0

感謝您的回覆。欣賞它。 但問題是,我不認爲我可以使用StringBuilder和子字符串函數等。 (不允許) –

+1

每次'a'的大小發生變化時,你想在數組'a'上進行排列而不改變循環嗎? – John

回答

3

排列與重複

當您有n個東西從......您有n個選擇,每次選擇!

當選擇其中的R,在排列是:

N×N×...(R倍)= N^R

我提出2例。第一種情況是當我們知道n和r的大小時,它是簡單的。第二個是n和r是動態的。

//when n and r are known statically 

class Permutation 
{ 
    public static void main(String[] args) 
    { 
     char[] values = {'a', 'b', 'c', 'd'}; 
     int n = values.length; 
     int r = 2; 

     int i = 0, j = 0; 
     for(i=0; i<n; i++) 
     { 
      for(j=0; j<n; j++) 
      { 
       System.out.println(values[j] + " " + values[i]); 
      } 
     } 
    } 
} 


//when n and r are known only dynamically 

class Permutation 
{ 
    public static void main(String[] args) 
    { 
     char[] values = {'a', 'b', 'c', 'd'}; 
     int n = values.length; 
     int r = 2; 
     int i[] = new int[r]; 
     int rc = 0; 
     for(int j=0; j<Math.pow(n,r); j++) 
     { 

      rc=0; 
      while(rc<r) 
      { 
       System.out.print(values[i[rc]] + " "); 
       rc++; 
      } 
      System.out.println(); 
      rc = 0; 
      while(rc<r) 
      { 
       if(i[rc]<n-1) 
       { 
        i[rc]++; 
        break; 
       } 
       else 
       { 
        i[rc]=0; 
       } 
       rc++; 
      } 
     } 
    } 
}