数据结构基础(7)

递归

  • 通过LeetCode上【70. 爬楼梯】学习

回溯

  • 利用回溯算法求解八皇后问题
public class WolfQueen {  
    /** 
     * 一共有多少个皇后(此时设置为8皇后在8X8棋盘,可以修改此值来设置N皇后问题) 
     */  
    int max = 8;  
    /** 
     * 该数组保存结果,第一个皇后摆在array[0]列,第二个摆在array[1]列 
     */  
    int[] array = new int[max];  
  
    public static void main(String[] args) {  
        new WolfQueen().check(0);  
    }  
  
    /** 
     * n代表当前是第几个皇后 
     * @param n 
     * 皇后n在array[n]列 
     */  
    private void check(int n) {  
        //终止条件是最后一行已经摆完,由于每摆一步都会校验是否有冲突,所以只要最后一行摆完,说明已经得到了一个正确解  
        if (n == max) {  
            print();  
            return;  
        }  
        //从第一列开始放值,然后判断是否和本行本列本斜线有冲突,如果OK,就进入下一行的逻辑  
        for (int i = 0; i < max; i++) {  
            array[n] = i;  
            if (judge(n)) {  
                check(n + 1);  
            }  
        }  
    }  
  
    private boolean judge(int n) {  
        for (int i = 0; i < n; i++) {  
            if (array[i] == array[n] || Math.abs(n - i) == Math.abs(array[n] - array[i])) {  
                return false;  
            }  
        }  
        return true;  
    }  
  
    private void print()  {  
        for (int i = 0; i < array.length; i++) {  
            System.out.print(array[i] + 1 + " ");  
        }  
        System.out.println();  
    }  
}  
  • 利用回溯算法求解 0-1 背包问题
public class Zero_One {
private static int[] p;//物品的价值数组
private static int[] w;//物品的重量数组
private static int c;//最大可以拿的重量
private static int count;//物品的个数

private static int cw;//当前的重量
private static int cp;//当前的价值
static int bestp;//目前最优装载的价值
private static int r;//剩余物品的价值

private static int[] cx;//存放当前解
private static int[] bestx;//存放最终解

public static int Loading(int[] ww,int[] pp, int cc) {
    //初始化数据成员,数组下标从1开始
    count = ww.length - 1;
    w = ww;
    p = pp;
    c = cc;
    cw = 0;
    bestp = 0;
    cx = new int[count+1];
    bestx = new int [count+1];

    //初始化r,即剩余最大价格
    for(int i = 1;i<=count;i++) {
        r += p[i];
    }

    //调用回溯法计算
    BackTrack(1);
    return bestp;   
}

/**
 * 回溯
 * @param t
 */
public static void BackTrack(int t) {
    if(t>count) {//到达叶结点
        if(cp>bestp) {
            for(int i = 1;i<=count;i++) {
                bestx[i] = cx[i];
            }

            bestp = cp;
        }
        return;
    }

    r -= p[t];
    if(cw + w[t] <= c) {//搜索左子树
        cx[t] = 1;
        cp += p[t];
        cw += w[t];
        BackTrack(t+1);
        cp -= p[t];//恢复现场
        cw -= w[t];//恢复现场

    }

    if(cp + r >bestp) {//剪枝操作
        cx[t] = 0;//搜索右子树
        BackTrack(t+1);
    }
    r += p[t];//恢复现场
}



public static void main(String[] args) {
    //测试
    int[] w1 = {0,15,25,40,20,15,24};
    int[] p1 = {0,10,5,20,2,14,23};
    int c1 = 30;
    Loading(w1,p1,c1);
    System.out.println("最优装载为:" + bestp);
    for(int i =1;i<=count;i++) {
        System.out.print(bestx[i] + " ");
    }           
}

分治

  • 利用分治算法求一组数据的逆序对个数
public class Main{
    
    public long count = 0;   //全局变量,使用合并排序,计算逆序对数
    //使用归并排序方法计算数组A中的逆序对数
    public void getReverseCount(int[] A) {
        if(A.length > 1) {
            int[] leftA = getHalfArray(A, 0);   //数组A的左半边元素
            int[] rightA = getHalfArray(A, 1);  //数组A的右半边元素
            getReverseCount(leftA);
            getReverseCount(rightA);
            mergeArray(A, leftA, rightA);
        }
    }
    //根据judge值判断,获取数组A的左半边元素或者右半边元素
    public int[] getHalfArray(int[] A, int judge) {
        int[] result;
        if(judge == 0) {   //返回数组A的左半边
            result = new int[A.length / 2];
            for(int i = 0;i < A.length / 2;i++)
                result[i] = A[i];
        } else {    //返回数组的右半边
            result= new int[A.length - A.length / 2];
            for(int i = 0;i < A.length - A.length / 2;i++)
                result[i] = A[A.length / 2 + i];
        }
        return result;
    }
    //合并数组A的左半边和右半边元素,并按照非降序序列排列
    public void mergeArray(int[] A, int[] leftA, int[] rightA) {
        int len = 0;
        int i = 0;
        int j = 0;
        int lenL = leftA.length;
        int lenR = rightA.length;
         while(i < lenL && j < lenR) {
             if(leftA[i] > rightA[j]) {
                 A[len++] = rightA[j++]; //将rightA[j]放在leftA[i]元素之前,那么leftA[i]之后lenL - i个元素均大于rightA[j]
                 count += (lenL - i);   //合并之前,leftA中元素是非降序排列,rightA中元素也是非降序排列。所以,此时就新增lenL - i个逆序对
             } else {
                 A[len++] = leftA[i++];
             }
         }
         while(i < lenL)
             A[len++] = leftA[i++];
         while(j < lenR)
             A[len++] = rightA[j++];
    }
    //获取一个随机数数组
    public int[] getRandomArray(int n) {
        int[] result = new int[n];
        for(int i = 0;i < n;i++) {
            result[i] = (int)( Math.random() * 50);  //生成0~50之间的随机数
        }
        return result;
    }
    
    public static void main(String[] args){
        long t1 = System.currentTimeMillis();
        Main test = new Main();
        int[] A = test.getRandomArray(50000);
        test.getReverseCount(A);
        long t2 = System.currentTimeMillis();
        System.out.println("分治法得到结果:"+test.count+", 耗时:"+(t2 - t1)+"毫秒");
    }
}

动态规划

  • 0-1 背包问题
public class Package_01 {
    public static int maxValue(int[] weight, int[] value, int capacity) {
        int weightLen = weight.length;
        int valueLen = capacity + 1;//列值长度加1,是因为最后一列要保证重量值为lenColumn
        int maxValue = 0;
        int[][] v = new int[weightLen][valueLen];
        for (int i = 0; i < weightLen; i++) {
            for (int j = 0; j < valueLen; j++) {
                if (i == 0) {
                    v[i][j] = 0;
                } else if (j == 0) {
                    v[i][j] = 0;
                } else {
                    if (weight[i] > j) {
                        v[i][j] = v[i - 1][j];
 
                    } else if (weight[i] <= j) {
                        v[i][j] = Math.max(v[i - 1][j], v[i - 1][j - weight[i]] + value[i]);
                    }
                    maxValue = v[i][j];
                }
 
            }
 
        }
        return maxValue;
    }
}
  • 最小路径和(详细可看 Minimum Path Sum)
  • 编程实现莱文斯坦最短编辑距离
  • 编程实现查找两个字符串的最长公共子序列
  • 编程实现一个数据序列的最长递增子序列
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值