生成1-n的排列(使用递归)

package suanfajingsai;

import java.util.Scanner;
//生成1-n的排列
public class P184 {
	void print_permutation(int n,int a[],int cur){
		if(cur==n){//递归的边界  
			int b=n;
			for(int i=0;i<n;i=i+b){
				System.out.print("("+a[i]+","+a[i+1]+","+a[i+2]+")");
				 
				//1 2 3 1 3 2 2 1 3 2 3 1 3 1 2 3 2 1 0
			}
		}else for(int i=1;i<=n;i++){
			int ok=1;
			for(int j=0;j<cur;j++){
				if(a[j]==i){
					ok=0;//如果之前这个数出现过  就不可以在使用了
				}
			}
			if(ok==1){//如果没有出现过  就放到此处
				a[cur]=i;
				print_permutation(n, a, cur+1); //递归调用
			}
		}
	}
	public static void main(String[] args) {
		int n;
		int a[]=new int [10000];
		Scanner sc=new Scanner(System.in);
		n=sc.nextInt();
		P184 p1=new P184();
		p1.print_permutation(n, a, 0);
	}

}

猜你喜欢

转载自blog.csdn.net/qq_37387363/article/details/79269940
今日推荐