劍指offer-輸出字符串所有種類的排列組合

 常規題,先校驗長度,不符合則直接輸出;符合則判斷是否爲最後一個字符,是則直接new對象輸出,不是則交換begin和i位置的數字,再用遞歸輸出。

public class Test28{
//    先校驗
    public static void permutation(char[] chars){
        if (chars.length<1 || chars==null){
            return;
        }
        permutation(chars,0);

    }
    public static void permutation(char[] chars,int begin){
        //如果是最後一個字符
        if (chars.length-1 == begin){
            new String(chars);
            System.out.println(new String(chars));
        }else {
            char tmp;
            for (int i = begin;i<chars.length;i++){
                tmp = chars[begin];
                chars[begin] = chars[i];
                chars[i] = tmp;
                permutation(chars,begin+1);
            }
        }

    }

    public static void main(String[] args) {
        char[] c1 = {'a', 'b', 'c'};
        permutation(c1);
        char[] c2 = {'a', 'b', 'c','d'};
        permutation(c2,2);
    }

}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章