[LeetCode]Longest Increasing Path in a Matrix(Java)
阿新 • • 發佈:2019-01-08
這道題我用最容易想的想法就是回溯法計算分別延四個方向計算,結果時間複雜度為O(n5),結果導致時間過長
程式碼如下
public class Solution { int max = 0; public int longestIncreasingPath(int[][] matrix) { for(int i = 0;i <matrix.length;i++){ for(int j = 0;j<matrix[i].length;j++){ go(matrix,i,j,0); } } return max; } public void go(int[][] matrix,int i,int j,int pathNum){ pathNum++; //System.out.println(pathNum); if(i-1>=0&&matrix[i-1][j] > matrix[i][j]) go(matrix,i-1,j,pathNum); if(i+1<matrix.length&&matrix[i+1][j] > matrix[i][j]) go(matrix,i+1,j,pathNum); if(matrix.length>0 && j-1>=0 &&matrix[i][j-1] > matrix[i][j]) go(matrix,i,j-1,pathNum); if(matrix.length>0 && j+1< matrix[0].length&&matrix[i][j+1]>matrix[i][j]) go(matrix,i,j+1,pathNum); max = Math.max(pathNum,max); }
後期看提示改用動態規劃做,即
if四個方向由比matrix[i][j]大的則dp[i][j] = max(四個方向比他大的+1);
else dp[i][j] = 1
時間複雜度為O(5n)
程式碼如下
2017/3/5public class Solution { int[][] dp; public int longestIncreasingPath(int[][] matrix) { if(matrix.length == 0) return 0; int max = 0; dp = new int[matrix.length][matrix[0].length]; for(int i = 0;i <matrix.length;i++){ for(int j = 0;j<matrix[i].length;j++){ max = Math.max(go(matrix,i,j),max); } } return max; } public int go(int[][] matrix,int i,int j){ if(dp[i][j]!=0) return dp[i][j]; dp[i][j] = 1; if(i-1>=0&&matrix[i-1][j] > matrix[i][j]) dp[i][j] = Math.max(1+go(matrix,i-1,j),dp[i][j]); if(i+1<matrix.length&&matrix[i+1][j] > matrix[i][j]) dp[i][j] = Math.max(1+go(matrix,i+1,j),dp[i][j]); if(matrix.length>0 && j-1>=0 &&matrix[i][j-1] > matrix[i][j]) dp[i][j] = Math.max(1+go(matrix,i,j-1),dp[i][j]); if(matrix.length>0 && j+1< matrix[0].length&&matrix[i][j+1]>matrix[i][j]) dp[i][j] = Math.max(1+go(matrix,i,j+1),dp[i][j]); return dp[i][j]; } }