---
title: "算法：全排列"
author: "The_Apocalypse"
date: "2013-07-04T11:28:30Z"
tags: []
categories: ["编程语言"]
slug: "untitled"
draft: false
lastmod: "2013-07-04T11:29:52Z"
id: 1898336
url: "https://the-apocalypse.iteye.com/blog/1898336"
---

全排列的算法实现Java版

程序如下：

 

```
package algorithm;

public class PermAndCombine {
	// 排列组合算法
	//真难理解啊
	//排列组合分很多种 理解的了吗
	//这是多层循环嵌套
	//这是全排列的算法
	//beg  end为数组下标
	public static void perm(int[] bu, int beg, int end) {
		if (beg == end) {
			for (int i = 0; i < bu.length; i++)
				Print.print(bu[i]);
			Print.println("");
		}
		else {
			for (int i = beg; i <= end; i++) {
				swap(bu, beg, i);
				perm(bu, beg + 1, end);
				swap(bu, beg, i);
			}
		}
	}
	//注意这个交换哈，单独给两个值可交换不了，也算有个传值传地址的问题吧
	//自内向外思考才行，程序也得自内向外写
	public static void swap(int[] buf, int a, int b) {
		if (a != b) {
			int temp = buf[a];
			buf[a] = buf[b];
			buf[b] = temp;
		}
	}
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		int[] a = { 1, 2, 3 ,4,5};
		perm(a, 0, 4);
	}
}
```

 

 结果太长，回去自个试下吧