|
| 1 | +package com.algorithm.study.demo.algorithm.leetcode; |
| 2 | + |
| 3 | +/** |
| 4 | + * @author xun2.liu |
| 5 | + * @title: Solution27 |
| 6 | + * @projectName algorithm-study |
| 7 | + * @description: 在一个 m*n 的棋盘的每一格都放有一个礼物,每个礼物都有一定的价值(价值大于 0)。 |
| 8 | + * 你可以从棋盘的左上角开始拿格子里的礼物,并每次向右或者向下移动一格、直到到达棋盘的右下角。 |
| 9 | + * 给定一个棋盘及其上面的礼物的价值,请计算你最多能拿到多少价值的礼物? |
| 10 | +
|
| 11 | + * 示例 1: |
| 12 | + * |
| 13 | + * 输入: |
| 14 | + * [ |
| 15 | + * [1,3,1], |
| 16 | + * [1,5,1], |
| 17 | + * [4,2,1] |
| 18 | + * ] |
| 19 | + * 输出: 12 |
| 20 | + * 解释: 路径 1→3→5→2→1 可以拿到最多价值的礼物 |
| 21 | + * 来源:力扣(LeetCode) |
| 22 | + * 链接:https://leetcode-cn.com/problems/li-wu-de-zui-da-jie-zhi-lcof |
| 23 | + * @date 2020/6/30 20:32 |
| 24 | + */ |
| 25 | +public class Solution27 { |
| 26 | + |
| 27 | + public static int maxValue(int[][] grid) { |
| 28 | + int row=grid.length; |
| 29 | + int col=grid[0].length; |
| 30 | + int[][] db=new int[row+1][col+1]; |
| 31 | + for (int i=1;i<=row;i++){ |
| 32 | + for (int j=1;j<=col;j++){ |
| 33 | + db[i][j]=Math.max(db[i-1][j],db[i][j-1])+grid[i-1][j-1]; |
| 34 | + } |
| 35 | + } |
| 36 | + return db[row][col]; |
| 37 | + } |
| 38 | + /** |
| 39 | + * 设 f(i, j) 为从棋盘左上角走至单元格 (i ,j)的礼物最大累计价值,易得到以下递推关系:f(i,j) |
| 40 | + * 等于 f(i,j-1) 和 f(i-1,j) 中的较大值加上当前单元格礼物价值 grid(i,j) |
| 41 | + * f(i,j)=max[f(i,j−1),f(i−1,j)]+grid(i,j) |
| 42 | + */ |
| 43 | + public static int maxValue2(int[][] grid) { |
| 44 | + int m = grid.length, n = grid[0].length; |
| 45 | + for(int i = 0; i < m; i++) { |
| 46 | + for(int j = 0; j < n; j++) { |
| 47 | + if(i == 0 && j == 0) { |
| 48 | + continue; |
| 49 | + } |
| 50 | + if(i == 0) { |
| 51 | + grid[i][j] += grid[i][j - 1] ; |
| 52 | + } else if(j == 0) { |
| 53 | + grid[i][j] += grid[i - 1][j]; |
| 54 | + } else { |
| 55 | + grid[i][j] += Math.max(grid[i][j - 1], grid[i - 1][j]); |
| 56 | + } |
| 57 | + } |
| 58 | + } |
| 59 | + return grid[m - 1][n - 1]; |
| 60 | + } |
| 61 | + public static void main(String[] args) { |
| 62 | + int[][] dd={{1,3,1},{1,5,1},{4,2,1}}; |
| 63 | + |
| 64 | + int i = maxValue(dd); |
| 65 | + System.out.println(i); |
| 66 | + } |
| 67 | +} |
0 commit comments