2012-08-30 94 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++; 
      } 
     } 
    } 
}