![]() |
#2
moox2018-02-27 12:22
|
为什么会time limit exceeded?
我尝试了下Debug code in playground ,结果run code时 一直显示在 runing。
是我写的代码效率达不到要求吗?
下面附上题目:
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
Example 1:
[[1,3,1],
[1,5,1],
[4,2,1]]
Given the above grid map, return 7. Because the path 1→3→1→1→1 minimizes the sum.

//my solution:
#define INF_MAX 100000000;
class Solution {
public:
int minPathSum(vector<vector<int> >& grid) {
if( grid.empty() ) return 0;
int minV=INF_MAX;
int sum=0;
searchPath(grid,0,0,grid.size()-1,grid[grid.size()-1].size()-1,
sum,minV);
return minV;
}
void searchPath(vector<vector<int> >& grid,
int startLine,int startRow,
const int& endLine,const int& endRow,
int sum,int& minV){
if(startLine==endLine && startRow==endRow){
minV=( minV > sum+grid[startLine][startRow] )?sum+grid[startLine][startRow]:minV;
return ;
}
if(grid[startLine][startRow] == -1)
return ;
int temp=grid[startLine][startRow];
if(startLine+1 <= endLine && sum+temp+grid[startLine+1][startRow] <= minV)
searchPath(grid,startLine+1,startRow,endLine,endRow,sum+temp,minV);
if(startRow+1 <= endRow && sum+temp+grid[startLine][startRow+1] <= minV)
searchPath(grid,startLine,startRow+1,endLine,endRow,sum+temp,minV);
}
};
#define INF_MAX 100000000;
class Solution {
public:
int minPathSum(vector<vector<int> >& grid) {
if( grid.empty() ) return 0;
int minV=INF_MAX;
int sum=0;
searchPath(grid,0,0,grid.size()-1,grid[grid.size()-1].size()-1,
sum,minV);
return minV;
}
void searchPath(vector<vector<int> >& grid,
int startLine,int startRow,
const int& endLine,const int& endRow,
int sum,int& minV){
if(startLine==endLine && startRow==endRow){
minV=( minV > sum+grid[startLine][startRow] )?sum+grid[startLine][startRow]:minV;
return ;
}
if(grid[startLine][startRow] == -1)
return ;
int temp=grid[startLine][startRow];
if(startLine+1 <= endLine && sum+temp+grid[startLine+1][startRow] <= minV)
searchPath(grid,startLine+1,startRow,endLine,endRow,sum+temp,minV);
if(startRow+1 <= endRow && sum+temp+grid[startLine][startRow+1] <= minV)
searchPath(grid,startLine,startRow+1,endLine,endRow,sum+temp,minV);
}
};
只有本站会员才能查看附件,请 登录
只有本站会员才能查看附件,请 登录
[此贴子已经被作者于2018-2-27 12:20编辑过]