所有排序

package corejava;

import java.util.LinkedHashSet;
import java.util.Set;

/**
 * (机能概要描述)
 * 
 * <pre>
 *  [变更履历]
 *  09.07.20.NICKLE NET 初版
 * </pre>
 * 
 * @author NICKLE)王
 */
public class Test {

	private static Set<String> set = new LinkedHashSet<String>();

	private static void perm(int[] arr, int k, int m) {
		if (k == m) {// 递归
			StringBuffer sb = new StringBuffer();
			for (int i = 0; i <= m; i++)
				sb.append(arr[i]);
			set.add(sb.toString());
		} else {
			for (int i = k; i <= m; i++) {
				arr[k] = (arr[k] + arr[i]) - (arr[i] = arr[k]); // 交换arr[k] <->
				// arr[i]
				perm(arr, k + 1, m);
				arr[k] = (arr[k] + arr[i]) - (arr[i] = arr[k]); // 交换arr[k] <->
				// arr[i]
			}
		}
	}

	public static String[] getPerm(int[] arr, int k, int m) {
		perm(arr, k, m);
		return set.toArray(new String[set.size()]);
	}

	public static void main(String[] args) {
		int[] test = { 1, 2, 3 };
		String[] perms = getPerm(test, 0, test.length - 1);
		for (String s : perms)
			System.out.println(s);
	}
}

你可能感兴趣的:(java,.net)