面试手撕代码(五)-动态规划

面试手撕代码(五)-动态规划

1.背包问题

public class Main {

	public static int backPack(int[] w, int[] v, int m){
        int[][] dp = new int[v.length+1][m+1];
        int[] items = new int[v.length+1];
        for (int i = 1; i <= v.length; i++) {
            for (int j = 1; j <= m; j++) {
                if(w[i-1]>j){
                    dp[i][j] = dp[i-1][j];
                }else{
                    dp[i][j] = Math.max(dp[i-1][j],dp[i-1][j-w[i-1]]+v[i-1]);
                }
            }
        }
        return dp[v.length][m];
    }
    public static void main(String[] args) throws Exception{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int n = Integer.parseInt(br.readLine());
        int m = Integer.parseInt(br.readLine());
        String[] strings = br.readLine().split(" ");
        int[] w = new int[n];
        int[] v = new int[n];
        for (int i = 0; i < w.length; i++) {
            w[i] = Integer.parseInt(strings[i]);
        }
        strings = br.readLine().split(" ");
        for (int i = 0; i < v.length; i++) {
            v[i] = Integer.parseInt(strings[i]);
        }
        System.out.println(backPack(w,v,m));
    }
}

2.机器人行走

/**
 *一个机器人从左上角出发,每次可以向下或向右走一步,求几种方式走到右下角
 * @author 
 *
 */

public class Mian {

	public static int uniquePaths(int m,int n){
		int[][] f=new int[m][n];
		for (int i = 0; i < m; i++) {//行
			for (int j = 0; j < n; j++) {//列
				if (i==0||j==0) {
					f[i][j]=1;
				}else {
					f[i][j]=f[i-1][j]+f[i][j-1];
				}
			}
		}
		return f[m-1][n-1];
	}
}

3.青蛙跳

/**
 *在n块石头分别在x轴的0,1........n-1位置,一直青蛙从0跳到n-1,如果青蛙在第i块石头上,他最多可以右跳距离a,问青蛙是否跳到石头n-1
 * @author 
 *
 */
public class Main{
	
	public static boolean conJump(int[] A){
		int n=A.length;
		boolean[] f=new boolean[n];
		f[0]=true;
		
		for (int j = 0; j < n; j++) {
			f[j]=false;
			for (int i = 0; i < j; i++) {
				if (f[i]&&i+A[i]>=i) {
					f[j]=true;
					break;
				}
			}
		}
			return f[n-1];	
	}
}

4.最小数

/**
 * 如果有三种硬币2 5 7,用这三种硬币凑出最少的硬币数,使得总数为27。
 * @author 
 *
 */
public class Main {
     public static void main(String[] args) {
		int[] A={500,1};
		int M=1000;
		System.out.println(coinChange(A,M));
	}
	
	//                           {2 5 7}    27
	public static int coinChange(int[] A,int M){
		int[] f=new int[M+1];
		int n=A.length;
		f[0]=0;
		//f[1],f[2],......,f[27]
		for (int i = 1; i <=M; i++) {
			f[i]=Integer.MAX_VALUE;
			//f[i]=min{f[i-A[0]]+1,.....,f[i-A[n-1]]+1}
			for (int j = 0; j < n; j++) {
				//避免i-A[j]是负数,并且避免f[i-A[j]]是无穷大
				if (i>=A[j]&&f[i-A[j]]!=Integer.MAX_VALUE) {
					f[i]=Math.min(f[i-A[j]]+1, f[i]);
				}
			}
		}
		if (f[M]==Integer.MAX_VALUE) {
			f[M]=-1;
		}
		return f[M];
	}
}

你可能感兴趣的:(java核心技术)