全排列算法

做了第三题-搭积木和 第六题-寒假作业,都用了全排列。


用dfs写全排列:

/*比如从1-9,思路:让a[1]-a[9]每个数从1-9遍历,用visit[10]
 *记录,如果用过了,置为false.*/

package test;


public class Main {
	static int count = 0;
	public static void main(String[] args) {
		int a[] = new int[10];
		boolean visit[] = new boolean[10];
		dfs(a,visit,1);
		System.out.println(count);
	}
	private static void dfs(int[] a, boolean[] visit, int num) {
		if (num==10) {
			count++;
			return;
		}
		
		for (a[num] = 1; a[num] <= 9; a[num]++) {
			if (judge(a)) {//这里根据情况剪枝,减少计算量
				if (visit[a[num]]==false) {
					visit[a[num]]=true;
					num = num + 1;
					dfs(a, visit, num);
					num = num -1;
					visit[a[num]]=false;
				}
			}else {
				continue;
			}
		}
	}
	private static boolean judge(int[] a) {
		
		return true;
	}
}



在网上又查到了效率高一点的全排列算法

package test;

public class Main {

	static int count = 0;
	
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		int a[] = new int[10];
		for (int i = 0; i < a.length; i++) {
			a[i] = i;
		}
		permulation(a, 0, a.length);
		System.out.println(count);
		
	}
	
	public static void permulation(int[] list, int start, int length ) {
        int i;
        if (start == length) {
        	if (juedje(list)) {//判断
        		count +=1;
			}
            
        } else {
            for (i = start; i < length; i++) {
                swap(list, start, i);
                permulation(list, start + 1, length);
                swap(list, start, i);
            }
        }
    }


	private static boolean juedje(int[] list) {
		return true;
	}

	public static void swap(int[] list, int start, int i) {
        int temp;
        temp = list[start];
        list[start] = list[i];
        list[i] = temp;
    }
}



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

obession

觉得有用可以打赏咖啡一杯~

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值