Andy 胡

导航

JAVA递归实现全排列

全排列(permutation)

排列组合概念

排列,就是指从给定n个数的元素中取出指定m个数的元素,进行排序

  

组合,则是指从给定n个数的元素中仅仅取出指定m个数的元素,不考虑排序

全排列

 以数字为例,全排列就是从“第一个数字”起,“每个数字”分别与它“后面的数字”交换,复杂度为O(n!)

图示

  1. A依次和BC交换
  2. 交换一次后不急(如AB交换后,不急着交换AC),target后移,再依次交换
  3. 直到target=最后一个数时,停止,输出
  4. 返回上一步(很明显,用递归)接着做,此时注意,要把换了的数再还回来

代码

package permutate;

public class Common {
	static void swap(char str[], int a, int b) {
		if (a == b) {
			return;
		}
		char temp = str[a];
		str[a] = str[b];
		str[b] = temp;
	}

	static void printArr(char str[]) {
		for (char c : str) {
			System.out.print(c + " ");
		}
		System.out.println();
	}
}

  

package permutate;

public class 图解全排列 {
    static int count = 0;

    static void permutation(char str[], int t) {
        if (t == str.length - 1) {
            // 3.停止
            System.out.print(++count + ": ");
            Common.printArr(str);
            return;
        }

        for (int i = t; i < str.length; i++) {
            Common.swap(str, t, i);
            // 2.递归
            permutation(str, t + 1);
            // 4.返回上层,换回来
            Common.swap(str, t, i);
        }
    }

    public static void main(String[] args) {
        char str[] = new String("ABC").toCharArray();
        // 1.从0开始
        permutation(str, 0);
    }
}

 

 

 

posted on 2017-12-16 01:27  talkwah  阅读(608)  评论(0编辑  收藏  举报