算法设计与分析代表性问题解法代码

阶乘函数

import java.util.Scanner;

public class factorial {
    
    

    public static int factorial (int n){
    
    
        if (n == 0) return 1;
        return n * factorial(n - 1);
    }

    public static void main(String[] args) {
    
    
        Scanner scan = new Scanner(System.in);
        int n = scan.nextInt();
        System.out.println(factorial(n));
    }
}

斐波那契数列

import java.util.Scanner;

public class fibonacci {
    
    

//    public static int fibonacci(int n) {
    
    
//        if (n <= 1) return 1;
//        return fibonacci(n - 1) + fibonacci(n - 2);
//    }

    public static int fibonacci(int n) {
    
    
        if (n == 0) return 0;
        if (n == 1 || n == 2) return 1;
        int pre = 1, cur = 1;
        for (int i = 3; i < n; i++) {
    
    
            int temp = pre + cur;
            pre = cur;
            cur = temp;
        }
        return cur;
    }

    public static void main(String[] args) {
    
    
        Scanner scan = new Scanner(System.in);
        int n = scan.nextInt();
        System.out.println(fibonacci(n));
    }
}

排列问题

 public static void perm(int[] array, int k, int m) {
    
    
        if (k == m) {
    
    
            for (int i = 0; i <= m; i++) {
    
    
                System.out.println(array[i]);
            }
            System.out.println();
        } else {
    
    
            for (int i = k; i <= m; i++) {
    
    
                swap(array, k, i);
                perm(array, k + 1, m);
                swap(array, k, i);
            }
        }
    }

二分搜索

public class binarySearch {
    
    

    public static int binarySearch(int[] array, int value) {
    
    
        int left = 0, right = array.length - 1;
        while (left <= right) {
    
    
            int mid = (left + right) / 2;
            if (array[mid] == value) {
    
    
                return mid;
            } else if (array[mid] < value) {
    
    
                left = mid + 1;
            } else {
    
    
                right = mid - 1;
            }
        }
        return -1;
    }

    public static void main(String[] args) {
    
    
        int[] array= {
    
    1, 2, 3, 4, 5, 6, 7};
        int value = 3;
        System.out.println(binarySearch(array, value));
    }
}

棋盘覆盖

public class chessBoard {
    
    

    static int board[][];
    static int tile = 1;

    public static void chessBoard(int tr, int tc, int dr, int dc, int size) {
    
    
        if (size == 1) return;
        int t = tile++;
        int s = size / 2;

        if (dr < tr + s && dc < tc + s) {
    
    
            chessBoard(tr, tc, dr, dc, s);
        } else {
    
    
            board[tr + s - 1][tc + s - 1] = t;
            chessBoard(tr, tc, tr + s - 1, tc + s - 1, s);
        }

        if (dr < tr + s && dc >= tc + s) {
    
    
            chessBoard(tr, tc + s, dr, dc, s);
        } else {
    
    
            board[tr + s - 1][tc + s] = t;
            chessBoard(tr, tc + s, tr + s - 1, tc + s, s);
        }

        if (dr >= tr + s && dc < tc + s) {
    
    
            chessBoard(tr + s, tc, dr, dc, s);
        } else {
    
    
            board[tr + s][tc + s - 1] = t;
            chessBoard(tr + s, tc, tr + s, tc + s - 1, s);
        }

        if (dr >= tr + s && dc >= tc + s) {
    
    
            chessBoard(tr + s, tc + s, dr, dc, s);
        } else {
    
    
            board[tr + s][tc + s] = t;
            chessBoard(tr + s, tc + s, tr + s, tc + s, s);
        }
    }

    public static void main(String[] args) {
    
    
        int k = 3;
        int size = (int) Math.pow(2, k);
        board = new int[size][size];
        chessBoard(0, 0, 1, 3, size);
        for (int i = 0; i < size; i++) {
    
    
            for (int j = 0; j < size; j++) {
    
    
                System.out.printf("%4d", board[i][j]);
            }
            System.out.println();
        }
    }
}

快速排序

package algorithm;

public class quickSort {
    
    

    public static void quickSort(int[] array, int left, int right) {
    
    
        if (left > right) return;
        int temp = array[left];
        int first = left;
        int last = right;
        while (first != last) {
    
    
            while (temp <= array[last] && first < last) {
    
    
                last--;
            }
            while (array[first] <= temp && first < last) {
    
    
                first++;
            }
            int data = array[first];
            array[first] = array[last];
            array[last] = data;
        }
        array[left] = array[first];
        array[first] = temp;
        quickSort(array, left, first - 1);
        quickSort(array, first + 1, right);
    }

    public static void main(String[] args) {
    
    
        int[] array = {
    
    1, 3, 5, 2, 8, 6, 9, 4, 7};
        quickSort(array, 0, array.length - 1);
        for (int i = 0; i < array.length; i++) {
    
    
            System.out.print(array[i] + " ");
        }
    }
}

合并排序

package algorithm;

public class sortMerge{
    
    

    public static void mergesort(int[] array, int first, int last, int[] temp) {
    
    
        if(first < last){
    
    
            int mid = (first + last) / 2;
            mergesort(array, first, mid, temp);
            mergesort(array, mid +1, last, temp);
            merge(array, first, last, mid, temp);
        }
    }

    public static void merge(int[] array, int first, int last, int mid, int[]temp) {
    
    
        int left = first, right = last, midNew = mid, midPlus = mid + 1, k = 0;
        while(left <= midNew && midPlus <= right){
    
    
            if(array[left] <= array[midPlus]){
    
    
                temp[k++] = array[left++];
            }else {
    
    
                temp[k++] = array[midPlus++];
            }
        }

        while(left <= midNew){
    
    
            temp[k++] = array[left++];
        }
        while(midPlus <= right){
    
    
            temp[k++] = array[midPlus++];
        }
        for(int i = 0; i < k; i++){
    
    
            array[first + i] = temp[i];
        }
    }

    public static void main(String[] args) {
    
    
        int[] array = {
    
    8, 5, 3, 1, 7, 2, 5, 9, 4};
        int n = array.length;
        int[] temp = new int[n];
        mergesort(array, 0, n-1, temp);
        for(int i = 0; i < n; i++){
    
    
            System.out.print(array[i] + " ");
        }
    }
}

两个矩阵连乘

import java.util.Scanner;

public class towMatrixMultiplication {
    
    

    public static void towMatrixMultiplication(int[][] arr1, int[][] arr2, int[][] arr3, int row1, int col1, int row2, int col2) throws IllegalAccessException {
    
    
        if (col1 != row2) {
    
    
            throw new IllegalAccessException("矩阵不能连乘!");
        }
        for (int i = 0; i < row1; i++) {
    
    
            for (int j = 0; j < col2; j++) {
    
    
                int sum = arr1[i][0] * arr2[0][j];
                for (int k = 1; k < col1; k++) {
    
    
                    sum += arr1[i][k] * arr2[k][j];
                }
                arr3[i][j] = sum;
            }
        }
    }

    public static void main(String[] args) throws IllegalAccessException {
    
    
        Scanner scan = new Scanner(System.in);
        int[][] arr1 = new int[2][3];
        int[][] arr2 = new int[3][4];
        int[][] arr3 = new int[2][4];
        for (int i = 0; i < 2; i++) {
    
    
            for (int j = 0; j < 3; j++) {
    
    
                arr1[i][j] = scan.nextInt();
            }
        }
        for (int i = 0; i < 3; i++) {
    
    
            for (int j = 0; j < 4; j++) {
    
    
                arr2[i][j] = scan.nextInt();
            }
        }
        towMatrixMultiplication(arr1, arr2, arr3, 2, 3, 3, 4);
        for (int i = 0; i < 2; i++) {
    
    
            for (int j = 0; j < 4; j++) {
    
    
                System.out.printf("%3d", arr3[i][j]);
            }
            System.out.println();
        }
    }
}

多个矩阵连乘

public class matrixMultiplication {
    
    

    public static void matrixMultiplication(int[] p, int[][]m, int[][]s) {
    
    
        int n = p.length - 1;
        for (int i = 0; i < n; i++) m[i][i] = 0;
        for (int r = 2; r <= n; r++) {
    
    
            for (int i = 0; i < n - r + 1; i++) {
    
    
                int j = i + r - 1;
                m[i][j] = m[i + 1][j] + p[i - 1] * p[i] * p[j];
                s[i][j] = i;
                for (int k  = i + 1; k < j; k++) {
    
    
                    int t = m[i][k] + m[k + 1][j] + p[i - 1] * p[k] * p[j];
                    if (t < m[i][j]) {
    
    
                        m[i][j] = t;
                        s[i][j] = k;
                    }
                }
            }
        }
    }

    public static void main(String[] args) {
    
    

    }
}

最长公共子序列

	public static int lcsLength(char[] x, char[] y, int[][] b) {
    
    
        int n = x.length - 1;
        int m = y.length - 1;
        int[][] c = new int[n + 1][m + 1];
        for (int i = 1; i <= n; i++) c[i][0] = 0;
        for (int j = 1; j <= m; j++) c[0][j] = 0;
        for (int i = 1; i <= n; i++) {
    
    
            for (int j = 1; j <= m; j++) {
    
    
                if (x[i] == y[j]) {
    
    
                    c[i][j] = c[i - 1][j - 1] + 1;
                    b[i][j] = 1;
                } else if (c[i - 1][j] >= c[i][j - 1]) {
    
    
                    c[i][j] = c[i - 1][j];
                    b[i][j] = 2;
                } else {
    
    
                    c[i][j] = c[i][j - 1];
                    b[i][j] = 3;
                }
            }
        }
        return c[n][m];
    }

    public static void lcs(int i, int j, char[] x, int[][]b) {
    
    
        if (i == 0 || j == 0) return;
        if (b[i][j] == 1) {
    
    
            lcs(i - 1, j - 1, x, b);
            System.out.print(x[i]);
        } else if (b[i][j] == 2) {
    
    
            lcs(i - 1, j, x, b);
        } else {
    
    
            lcs(i, j - 1, x, b);
        }
    }

活动安排问题

//活动安排

public class greedySelector {
    
    

    public static int greedySelector(int[] startTime, int[] finishTime, boolean[] activity) {
    
    
        int n = startTime.length - 1;
        activity[1] = true;
        int j = 1;
        int count = 1;
        for (int i = 2; i <= n; i++) {
    
    
            if (startTime[i] >= finishTime[j]) {
    
    
                activity[i] = true;
                j = i;
                count++;
            } else {
    
    
                activity[i] = false;
            }
        }
        return count;
    }

    public static void main(String[] args) {
    
    
        int[] startTime = {
    
    1,3,0,5,3,5,6,8,2,12};
        int[] finishTime = {
    
    4,5,6,7,8,9,10,11,12,13,14};
        boolean[] activity = new boolean[startTime.length];
        //greedySelector gs = new greedySelector();
        int count = greedySelector(startTime, finishTime, activity);
        System.out.println("能够进行活动的容量:" + count);
        for(int i = 1; i <= startTime.length - 1; i++){
    
    
            if(activity[i] == true){
    
    
                System.out.println("第" + i + "个活动能够进行,其开始时间为:" + startTime[i] + ",结束时间为:" + finishTime[i]);
            }
        }
    }
}

0-1背包问题——贪心解法

//0-1 背包问题 —— 贪心解法

public class knapsack {
    
    

    public static float knapsack(float capacity, float[] weight, float[] value, float[] x) {
    
    
        int n = value.length;
        Element[] d = new Element[n];
        for (int i = 0; i < n; i++) {
    
    
            d[i] = new Element(weight[i], value[i], i);
        }
        //MergeSort.mergeSort(d);
        int i;
        float opt = 0;
        for (i = 0; i < n; i++) x[i] = 0;
        for (i = 0; i < n; i++) {
    
    
            if (d[i].weight > capacity) break;
            x[d[i].i] = 1;
            opt += d[i].value;
            capacity -= d[i].weight;
        }
        if (i < n) {
    
    
            x[d[i].i] = capacity / d[i].weight;
            opt += x[d[i].i] * d[i].value;
        }
        return opt;
    }

    public static class Element implements Comparable {
    
    
        float value;
        int i;
        float weight;
        float key;
        float index;
        boolean job;

        private Element(float kk, float ii, boolean jj) {
    
    
            key = kk;
            index = ii;
            job = jj;
        }

        @Override
        public int compareTo(Object x) {
    
    
            int Ikey = ((flowShop.Element) x).key;
            if (key < Ikey) return - 1;
            if (key == Ikey) return 0;
            return 1;
        }
    }
}

最优装载问题

//最优装载——贪心算法

public class loading {
    
    

    public static float loading(float capacity, float[] weight, int[] x) {
    
    
        int n = weight.length;
        Element[] d = new Element[n];
        for (int i = 0; i < n; i++) {
    
    
            d[i] = new Element(weight[i], i);
        }
        //MergeSort.mergeSort(d);
        float opt = 0;
        for (int i = 0; i < n; i++) x[i] = 0;
        for (int i = 0; i < n && d[i].weight <= capacity; i++) {
    
    
            x[d[i].i] = 1;
            opt += d[i].weight;
            capacity -= d[i].weight;
        }
        return opt;
    }
    
    public static class Element implements Comparable {
    
    
        float weight;
        int i;
        public Element(float ww, int ii) {
    
    
            weight = ww;
            i = ii;
        }
        
        @Override
        public int compareTo(Object o) {
    
    
            Object x = null;
            float xw = ((Element) x).weight;
            if (weight < xw) return - 1;
            if (weight == xw) return 0;
            return 1;
        }
    }
}

0-1背包——回溯法

//0-1背包——回溯法

public class knapsackBack {
    
    
    private static class Element implements Comparable {
    
    
        //物品编号
        int id;
        private double d;

        private Element(int idd, double dd) {
    
    
            id = idd;
            d = dd;
        }

        @Override
        public int compareTo(Object x) {
    
    
            double xd = ((Element) x).d;
            if (d < xd) return - 1;
            if (d == xd) return 0;
            return 1;
        }

        public boolean equals(Object x) {
    
    
            return d == ((Element) x).d;
        }

        static double c;    //背包容量
        static int n;       //物品数
        static double[] w;  //物品重量数组
        static double[] p;  //物品价值数组
        static double cw;   //当前重量
        static double cp;   //当前价值
        static double best; //当前最优解

        public static double knapsack(double[] pp, double[] ww, double cc) {
    
    
            c = cc;
            n = pp.length - 1;
            cw = 0.0;
            cp = 0.0;
            best = 0.0;

            //q为单位重量价值数组
            Element[] q = new Element[n];

            for (int i = 1; i <= n; i++) {
    
    
                q[i - 1] = new Element(i, pp[i] / ww[i]);
            }

            //将各物品依单位重量价值从大到小排序
            //MergeSort.mergeSort(q);

            p = new double[n + 1];
            w = new double[n + 1];
            for (int i = 1; i <= n; i++) {
    
    
                p[i] = pp[q[n - 1].id];
                w[i] = ww[q[n - 1].id];
            }
            backtrack(1);   //回溯搜索
            return best;
        }

        private static void backtrack(int i) {
    
    
            //到达叶子节点
            if (i > n) {
    
    
                best = cp;
                return;
            }
            //搜索子树
            if (cw + w[i] <= c) {
    
    
                cw += w[i];
                cp += p[i];
                backtrack(i + 1);
                cw -= w[i];
                cp -= p[i];
            }
            if (bound(i + 1) > best) {
    
    
                //进入右子树
                bound(i + 1);
            }
        }

        private static double bound(int i) {
    
    
            //计算上界
            //剩余容量
            double cleft = c - cw;
            double bound = cp;
            //以物品单位重量价值递减顺序装入物品
            while (i <= n && w[i] <= cleft) {
    
    
                cleft -= w[i];
                bound += p[i];
                i++;
            }

            //装满背包
            if (i <= n) {
    
    
                bound += p[i] * cleft / w[i];
            }
            return bound;
        }
    }
}

装载问题——分支界限

//装载问题——分支界限

import java.util.LinkedList;
import java.util.Queue;

public class FIFOBBLoading {
    
    
    static int n;
    static int best;
    static Queue queue;

    public static int maxLoading(int[] w, int c) {
    
    
        n = w.length - 1;
        best = 0;
        queue = new LinkedList<>();
        queue.offer(new Integer(-1));

        int i = 1;
        int ew = 0;

        while (true) {
    
    
            if (ew + w[i] <= c) {
    
    
                enQueue(ew + w[i], i);
            }
            enQueue(ew ,i);
            ew = ((Integer)queue.remove()).intValue();
            if (ew == - 1) {
    
    
                if (queue.isEmpty()) return best;
                queue.offer(new Integer(- 1));
                ew = ((Integer)queue.remove()).intValue();
                i++;
            }
        }
    }

    private static void enQueue(int wt, int i) {
    
    
        if (i == n) {
    
    
            if (wt > best) best = wt;
            else queue.offer(new Integer(wt));
        }
    }

}

猜你喜欢

转载自blog.csdn.net/weixin_43356538/article/details/114337607