利用递归实现 把word 这个单词输出为:word,wro,wrd,wod,rod,wo,wr,wd,dr,od,or,w,o,r,d和空值不需要按顺序,包括字母的顺序,只要能输出这16个集合就行这个程序该怎么写啊?下面是老师上课时讲到的东西。
public class Permutations 
{
 //Attributes
    private static String word;
    //Constructor
    public Permutations(String w)
    {
        Permutations.word=w;
    }
    Permutations p;
    //Method
    public ArrayList<String> getPermutations()
    {
        ArrayList<String> list=new ArrayList<String>();
        //Base part
        if(word.length()==0)
        {
//          list.add(word);
            System.out.println();
        }
        //Recursive part
        if (word.length() > 0)
        for(int i=1;i<word.length();i++)
        {
         System.out.println(word.substring(0, i));
        
            //Find all permutations of the rest of the characters
      p=new Permutations(word.substring(0,i)+word.substring(i+1));
      ArrayList<String> shortOnes=p.getPermutations();
      for(String s:shortOnes)
      {
          list.add(word.charAt(i)+s);
      }       }
               return list;
    }
    public static void main(String[] args)
    {
   Permutations per=new Permutations("word");
   per.getPermutations();
   }
}

解决方案 »

  1.   

    import java.util.HashSet;
    import java.util.Set;public class Test3 { private static Set<String> set = new HashSet<String>();
    public static void main(String args[]) {

    String str = new String("word");
    new Test3().goSplit(str);

    for(String s : set) {
    System.out.println(s);
    }
    }

    public void goSplit(String str) {
    if(str.length() >= 1) {
    set.add(str);
    for(int i = 0; i < str.length(); i++) {
    Character c = str.charAt(i);
    String newStr = str.replace(c.toString(), "");
    goSplit(newStr);
    set.add(newStr);
    }
    }else {
    return ;
    }
    }
    }
    测试成功,版主自己试下。