前言:为了后续的实习面试,开始疯狂刷题,非常欢迎志同道合的朋友一起交流。因为时间比较紧张,目前的规划是先过一遍,写出能想到的最优算法,第二遍再考虑最优或者较优的方法。如有错误欢迎指正。博主首发CSDN,mcf171专栏。
博客链接:mcf171的博客
——————————————————————————————
Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right which minimizes the sum of all numbers along its path.
Note: You can only move either down or right at any point in time.
这个题目和63的解法差不多,只是判断和赋值稍作改变,我比较意外的是效率居然高出其他人这么多。 Your runtime beats 97.44% of java submissions.
public class Solution {
public class TreeNode{
int down;
int right;
TreeNode(int down,int right){
this.down = down;
this.right = right;
}
}
public int minPathSum(int[][] grid) {
int m = grid.length;
if( m == 0 ) return 0;
int n = grid[0].length;
if( m == 1 && n == 1) return grid[0][0];
return goDeep(new TreeNode(m-1,n-1),0,0,grid);
}
public int goDeep(TreeNode node, int i, int j, int[][]nums){
if(node.down ==0 && node.right ==0) return nums[i][j];
int downSum = Integer.MAX_VALUE, rightSum = Integer.MAX_VALUE;
if(node.down > 0) {
if(nums[i+1][j] >= 0) {
downSum = goDeep(new TreeNode(node.down - 1, node.right), i + 1, j, nums);
nums[i + 1][j] = -downSum;
}else downSum = -nums[i+1][j];
}
if(node.right > 0) {
if(nums[i][j+1] >= 0) {
rightSum = goDeep(new TreeNode(node.down, node.right - 1), i, j + 1, nums);
nums[i][j + 1] = -rightSum;
}else rightSum = -nums[i][j+1];
}
int result = Math.min(downSum,rightSum) + nums[i][j];
return result;
}
}