首页 > 代码库 > 通过递归方法对一个单词所有的组合进行列举(java)

通过递归方法对一个单词所有的组合进行列举(java)

 1 import java.io.BufferedReader;
 2 import java.io.IOException;
 3 import java.io.InputStreamReader;
 4 
 5 public class Anagram{
 6     static int size;
 7     static int count;
 8     static String [] arr=new String[100];
 9     public static void main(String[] args) throws IOException {
10         System.out.println("Enter a word");
11         String input=getString();
12         size=input.length();
13         count=0;
14         for(int i=0;i<size;i++)
15         {
16             arr[i]=input.charAt(i)+"";
17         }
18         doAnaram(size);
19     }
20 
21     public static void rotate(int s) {
22         int j;
23         int position=size-s;
24         String temp=arr[position];
25         for(j=position+1;j<size;j++)
26             arr[j-1]=arr[j];
27         
28         arr[size-1]=temp;
29         
30     }
31 
32     public static void doAnaram(int length) {
33         if(length==1)
34             return ;
35         for(int i=0;i<length;i++)
36         {
37             doAnaram(length-1);
38             if(length==2)
39                 {
40                 dispalyword();
41                 }
42             rotate(length);
43         }
44         
45     }
46 
47 
48     public  static void dispalyword() {
49     for(int i=0;i<size;i++)
50     {
51         
52         System.out.print(arr[i]+" ");
53     }
54         System.out.print("\t");
55     }
56 
57     public static String getString() throws IOException {
58         InputStreamReader isr=new InputStreamReader(System.in);
59         BufferedReader br=new BufferedReader(isr);
60         String s=br.readLine();
61         return s;
62     }
63 }

 效果图