论坛首页 综合技术论坛

排列的递归实现

浏览 1842 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (3) :: 隐藏帖 (0)
作者 正文
   发表时间:2009-11-27   最后修改:2010-08-02
递归实现排列的打印功能

	public static void main(String[] args) throws Exception {
		perm(new String[] { "a", "b", "c", "d" });
		System.out.println();
		perm(new String[] { "a", "b", "c", "d" }, 2);
		System.out.println();
		perm(new String[] { "a", "b", "c", "d" }, 0);
	}

	// 全排列入口
	private static void perm(String[] a) {
		if (a != null) {
			perm(a, 0, a.length);
		}
	}

	// 部分排列入口
	private static void perm(String[] a, int count) {
		if (a != null && count >= 0 && count <= a.length) {
			perm(a, 0, count);
		}
	}

	private static void perm(String[] a, int start, final int count) {

		if (start == count) {
			for (int i = 0; i < count; i++) {
				System.out.print(a[i] + ", ");
			}
			System.out.println();
		} else {
			for (int i = start; i < a.length; i++) {
				swap(a, start, i);
				perm(a, start + 1, count);
				swap(a, start, i);
			}
		}
	}

	private static void swap(String[] a, int i, int j) {
		String t = a[i];
		a[i] = a[j];
		a[j] = t;
	}
论坛首页 综合技术版

跳转论坛:
Global site tag (gtag.js) - Google Analytics