日期:2014-05-20  浏览次数:20771 次

java数据结构算法里的变位字程序有一个地方搞不懂,请高人指教
import   java.io.BufferedReader;
import   java.io.IOException;
import   java.io.InputStreamReader;


public   class   AnagramApp   {

static   int   size;
static   int   count;
static   char[]   arrChar   =   new   char[100];

public   static   void   main(String[]   args)   throws   IOException   {
System.out.println( "Enter   a   word:   ");
String   input   =   getString();
size   =   input.length();
count   =   0;
for(int   j   =   0;   j   <   size;   j++){
arrChar[j]   =   input.charAt(j);
}
doAnagram(size);
}

public   static   void   doAnagram(int   newSize)   {
if(newSize   ==   1)   {
return;
}

for(int   j   =   0;   j   <   newSize;   j++)   {
doAnagram(newSize   -   1);
if(newSize   ==   2){//为什么把这行的if条件去掉打印出来的单词就会有重复呢?虽然凭感觉认为需要这个if条件,但是不知道真正的原因是什么,也就是不知道怎么证明出来。唉,本人数学差。。。
displayWord();
}
rotate(newSize);
}
}

public   static   void   rotate(int   newSize)   {
int   j;
int   position   =   size   -   newSize;
char   temp   =   arrChar[position];

for(j   =   position   +   1;   j   <   size;   j++)   {
arrChar[j   -1]   =   arrChar[j];
}
arrChar[j-1]   =   temp;
}

public   static   void   displayWord()   {
if(count   <   99)   {
System.out.print( "   ");
}

if(count   <   9)   {
System.out.print( "   ");
}

System.out.print(++count   +   "   ");
for(int   j   =   0;   j   <   size;   j++){
System.out.print(arrChar[j]);
}
System.out.print( "     ");
System.out.flush();
if(count   %   6   ==   0)   {
System.out.println( " ");
}
}

public   static   String   getString()   throws   IOException   {
InputStreamReader   isr   =   new   InputStreamReader(System.in);
BufferedReader   br   =   new   BufferedReader(isr);
String   s   =   br.readLine();
return   s;
}
}


------解决方案--------------------
我是新手 上面的问题还在等我升星拉
在来帮你解决问题吧
------解决方案--------------------
好头大的递归啊!
------解决方案--------------------
你这个是全排列的问题,其实这里的if(newSize == 2)就是每次递归到最后只剩下两个字符时(用书上的话讲就是把前缀排好,再把后缀加上去,直到标号相等)输出.在算法设计上的全排列问题中有相同的思想!!建议楼主去看看