全排列

Problem

Print all permutations of n distinct elements.

Solution

class Permutation {
    public static void main(String[] argument) {
        int[] list = { 1, 2, 3, 4 };
        Permutation.Perm(list, 0);
    }

    private static void Swap(int[] list, int i, int j) {
        int temp = list[i];
        list[i] = list[j];
        list[j] = temp;
    }

    public static void Perm(int[] list, int preceding) {
        int length = list.length;

        if (preceding == length - 1) {
            for (int i = 0; i < list.length; ++i)
                System.out.print(list[i] + " ");
            System.out.println();
        } else {
            for (int i = preceding; i < length; ++i) {
                Swap(list, preceding, i);
                Perm(list, preceding + 1);
                Swap(list, preceding, i);
            }
        }
    }
}

Output

1 2 3 4 
1 2 4 3 
1 3 2 4 
1 3 4 2 
1 4 3 2 
1 4 2 3 
2 1 3 4 
2 1 4 3 
2 3 1 4 
2 3 4 1 
2 4 3 1 
2 4 1 3 
3 2 1 4 
3 2 4 1 
3 1 2 4 
3 1 4 2 
3 4 1 2 
3 4 2 1 
4 2 3 1 
4 2 1 3 
4 3 2 1 
4 3 1 2 
4 1 3 2 
4 1 2 3 


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