ITeye博客

How to generate permutations recursively

standalone · 2011-06-18 17:02 · java · 编程语言 · Markdown

I have posted code to calcuate permutations in order,  this is another more short recursive one of generating non-order permutations.

package alg_test;

public class Permutation2 {
	void swap(int a[], int i, int j)
	{
		int temp = a[i];
		a[i]=a[j];
		a[j]= temp;
	}
	
	void printArray(int a[]){
		for(int i=0;i<a.length;i++) System.out.print("\t"+a[i]);
		System.out.println("");
	}
	public void permutate(int a[], int start, int end){
		if(start == end){
			printArray(a);
		}
		else {
			for(int i=start;i<=end;i++){
				swap(a, i, start);
				permutate(a, start+1, end);
				swap(a, i, start);
			}
		}
	}
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		int a[]={1,2,3,4};
		Permutation2 p  = new Permutation2();
		p.permutate(a, 0, a.length-1);
	}

}

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。