关于回溯的两个经典问题

1.利用回溯算法求解八皇后问题

   //用来记录各个棋子的位置,下标表示行,元素值代表列
   int [] result = new int[8];

    //依次存放每个行
    public void cal8queues(int row){
        if(row == 8){
            printqueens(result);
	
	   // 由于是递归的解法,所以每找到一种解法,就需要返回
            return;
        }
	//依次遍历每一列,看看那一列是合法的
        for(int column = 0; column < 8; column++){
            if(isOK(row,column)){
                result[row] = column;
                cal8queues(row + 1);
            }
        }
    }
    //判断某一行中的棋子应该放在哪一列
    public boolean isOK(int row, int column){
        int leftup = column - 1;
        int rightup = column + 1;

        for(int i = row - 1; i >=0; i--){
            if(result[i] == column) return false;
            if(leftup >= 0){
                if(result[i] == leftup) return false;
            }
            if(rightup < 8){
                if(result[i] == rightup) return false;
            }
		
	    // 当不断地向上面更小地行检索时,应当变更 left,right 的大小
            leftup--;
            rightup++;
        }
        return true;
    }
	
    //打印出合法的位置
    public void printqueens(int [] result) {
        for (int row = 0; row < 8; row++) {
            for (int column = 0; column < 8; column++) {
                if (result[row] == column) System.out.print("Q" + " ");
                else System.out.print("*" + " ");
            }
            System.out.println();
        }
        System.out.println();
    }

2.利用回溯算法求解 0-1 背包问题

 public int maxW = Integer.MIN_VALUE;

    public void f(int i, int cw, int[] items, int n, int w){
        if (cw == w || i == n) {
            if (cw > maxW) maxW = cw;
            return;
        }
        f(i+1, cw, items, n, w);
        if (cw + items[i] <= w) {
            f(i+1,cw + items[i], items, n, w);
        }
    }

转载于:https://my.oschina.net/happywe/blog/3059355

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值