全排列

题目:给出三个字符,求它们的全排列 , 比如 a , b , c   应该输出   abc acb bac bca cab cba六种

public static void permutation(char[] str , int first,int end) {
        //输出str[first..end]的所有排列方式

        //完成一次排列
        if(first == end) {    //输出一个排列方式
            for(int j=0; j<= end ;j++) {
                System.out.print(str.toString());
            }
            System.out.println();
        }

        //   a  b  c   i = 0到2
        // i = 0  1. abc  i = 1 到 2
        for(int i = first; i <= end ; i++) {
            swap(str, i, first);
            permutation(str, first+1, end);  //固定好当前一位,继续排列后面的
            swap(str, i, first);
        }
    }

    private static void swap(char[] str, int i, int first) {
        char tmp;
        tmp = str[first];
        str[first] = str[i];
        str[i] = tmp;
    }
    public static void main(String[] args) {
            char[] str = {'a', 'b', 'c',};
            permutation(str, 0, 2);
    }

 

posted @ 2017-06-26 13:25  雪浪snowWave  阅读(117)  评论(0编辑  收藏  举报