zoukankan      html  css  js  c++  java
  • 数组元素全排列递归算法

    /**
     * 使用的是递归算法实现集合内元素的全排列
     * @author height
     *
     */
    public class AllSort 
    {
    	int n;//记录总的个数
    	static int temp[];//记录自然数的数组
    	
    	/**
    	 * 用于交换数组中位置n1和n2的数
    	 * @param n1
    	 * @param n2
    	 */
    	void swap(int n1,int n2)
    	{
    		int tem = temp[n1];
    		temp[n1] = temp[n2];
    		temp[n2] = tem;
    	}
    	/**
    	 * 递归方法,思想:
    	 * 求集合P={r1,r2,r3,...,rn}的全排列。设Pt(r1)是指在集合P中去除元素r1后的集合,也就是r1相对于P的补集
    	 * 则P的全排列Perm(P)=r1Perm(Pt(r1))+r2Perm(Pt(r2))+...+rnPerm(Pt(rn)).
    	 * 由此,将n规模的全排列降为了n-1规模的全排列,此为该递归的基本思想。直到n=1的时候一个元素的全排列是自己
    	 * @param num  存集合的数组 本例中使用自然数
    	 * @param k    第一个元素在数组中的位置
    	 * @param m    最后一个元素在数组中的位置
    	 */
    	void perm(int num[],int k,int m)
    	{
    		int i;
    		if(k>m)
    		{
    			for(i = 0 ;i<=m;i++)
    			{
    				System.out.print(temp[i]+" ");
    			}
    			System.out.println();
    			n++;
    		}
    		else
    		{
    			for(i = k;i<=m;i++)
    			{
    				swap(k,i);
    				perm(temp,k+1,m);
    				swap(k,i);
    			}
    			
    		}
    	}
    	/**
    	 * 测试方法
    	 * @param args
    	 */
    	public static void main(String args[])
    	{
    		int tem[] = {1,2,3};
    		AllSort as = new AllSort();
    		as.temp = tem;
    		as.perm(temp, 0, 2);		
    	}
    	
    }
    

      

  • 相关阅读:
    IE11和传统asp.net的兼容问题
    时区和夏令时
    GTA项目 三, 使用 bootstrap table展示界面,使得data和UI分离
    GTA项目 二, JSON接口开放跨域访问
    GTA项目 一, 包装外部WebService
    DNS域名解析
    CRM 迁移服务器备忘
    CentOS6.5 安装HAProxy 1.5.20
    Custom IFormatProvider
    数据分区考虑
  • 原文地址:https://www.cnblogs.com/height/p/2638802.html
Copyright © 2011-2022 走看看