Java实现全排列

来源:互联网 发布:it团队建设方案 编辑:程序博客网 时间:2024/04/28 13:38

鉴于最近在面试,需要复习一下算法什么的,就把之前写的一些算法程序发出来。

public class Test {public static char[] text = { 'a', 'c', 'c', 'd' };public static void main(String[] args) {permutation(text, 0, text.length);System.exit(0);}/** * 全排列输出 *  * @param a *            [] 要输出的字符数组 * @param m *            输出字符数组的起始位置 * @param n *            输出字符数组的长度 */public static void permutation(char a[], int m, int n) {if (m < n - 1) {permutation(a, m + 1, n); // 从第2个元素开始全排列// 以后从第2个元素开始与第一个元素交换,再从第2个元素开始全排列// 最后还原序列,进行循环char t;for (int i = m + 1; i < n; i++) {if (a[m] != a[i]) {t = a[m]; // 交换a[m] = a[i];a[i] = t;permutation(a, m + 1, n);t = a[m]; // 还原a[m] = a[i];a[i] = t;}}} else {printResult(a);}}/** * 输出指定字符数组 */public static void printResult(char[] text) {for (int i = 0; i < text.length; i++) {System.out.print(text[i]);}System.out.println();}}




2 1
原创粉丝点击