`
standalone
  • 浏览: 611161 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

How to generate permutations recursively

    博客分类:
  • java
J# 
阅读更多

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);
	}

}
 
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics