递归_变位字

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Anagram {
    static int size;//变位字有的总字符个数
    static int count;//变位字变化之后共有多少个
    static char[] arrChar=new char[100];
    public static void main(String[] args) throws IOException {
        System.out.print("输入 一个word:");
        String word=getString();
        size=word.length();
        count=0;
        for(int j=0;j<size;j++) {
            arrChar[j]=word.charAt(j);//将字符串转换为数组
        }        
        doAnagram(size);

    }
    
    private static void doAnagram(int newSize) {
        if(newSize==1)
            return;
        for(int j=0;j<newSize;j++) {            
            if(newSize==2)
                displayWord();//打印(当只剩下两个数时,就可以打印数组)            
            doAnagram(newSize-1);//先让数据量为n-1的下标为n-1以后的数组变位            
            rotate(newSize);//转动当前数组(就是将数组中的每一个往前移动一位,第一个就移动到最后一个位置)            
        }        
    }
    /*
     * 2345
     * 第一层     第二层   第三层 
     * 2      3    4 
     *             5 
     *        4    5
     *             3
     *        5    3
     *             4
     * 3      4    5
     *             2
     *        5    2
     *             4
     *        2    4
     *             5
     * 4      5    2
     *             3
     *        2    3
     *             5
     *        3    5
     *             2
     * 5      2    3
     *             4
     *        3    4
     *             2
     *        4    2
     *             3
     * 
     * 
     * 
     * 
     * 
     * 
     * 
     */

    private 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;
        
    }
    private static void displayWord() {
        if(count<99)
            System.out.print(" ");
        if(count<9)
            System.out.print(" ");//当count的数值为一位数,两位数,三位数时,输出都会影响排版,所以需要在一位数的count前面加上一个空格,两位数前面加上一个空格。最后数据显示的都在同一条线上
        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 inputStreamReader=new InputStreamReader(System.in);
        BufferedReader bufferedReader=new BufferedReader(inputStreamReader);
        return bufferedReader.readLine();

    }
    

}
原文地址:https://www.cnblogs.com/S-Mustard/p/8098007.html