【Lintcode】398. Longest Continuous Increasing Subsequence II
題目地址:
https://www.lintcode.com/problem/longest-continuous-increasing-subsequence-ii/description
給定一個二維矩陣 A A A,從某個位置出發,可以向上下左右走一步。問由嚴格上升數字構成的最長路徑的長度。
思路是記憶化搜尋。設 f [ i ] [ j ] f[i][j] f[i][j]是從 A [ i ] [ j ] A[i][j] A[i][j]出發的最長上升路徑的長度,則 f [ i ] [ j ] f[i][j] f[i][j]可以由 1 1 1加上四周比 A [ i ] [ j ] A[i][j] A[i][j]大的數出發的最長上升路徑的長度來更新。如果不存在,那麼 f [ i ] [ j ] = 1 f[i][j]=1 f[i][j]=1。程式碼如下:
public class Solution {
/**
* @param matrix: A 2D-array of integers
* @return: an integer
*/
public int longestContinuousIncreasingSubsequence2(int[][] matrix) {
// write your code here
if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
return 0;
}
int m = matrix.length, n = matrix[0].length;
int[][] dp = new int[m][n];
int res = 0;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
res = Math.max(res, dfs(i, j, dp, matrix));
}
}
return res;
}
private int dfs(int x, int y, int[][] dp, int[][] matrix) {
// 有記憶,則調取記憶
if (dp[x][y] != 0) {
return dp[x][y];
}
// 先初始化為1
dp[x][y] = 1;
int[] d = {1, 0, -1, 0, 1};
for (int i = 0; i < 4; i++) {
int nextX = x + d[i], nextY = y + d[i + 1];
// 如果沒出界,並且可以接上去,就繼續DFS
if (0 <= nextX && nextX < matrix.length && 0 <= nextY && nextY < matrix[0].length && matrix[nextX][nextY] > matrix[x][y]) {
dp[x][y] = Math.max(dp[x][y], 1 + dfs(nextX, nextY, dp, matrix));
}
}
return dp[x][y];
}
}
時空複雜度 O ( m n ) O(mn) O(mn)。
相關文章
- LintCode-Longest Increasing Subsequence
- [LeetCode] 674. Longest Continuous Increasing SubsequenceLeetCode
- [LintCode] Longest Increasing Subsequence 最長遞增子序列
- LeetCode-Longest Increasing SubsequenceLeetCode
- LintCode-Longest Common Subsequence
- LeetCode-Increasing Triplet SubsequenceLeetCode
- 【LeetCode】Increasing Triplet Subsequence(334)LeetCode
- LeetCode-Longest Increasing Path in a MatrixLeetCode
- Lintcode 1263. Is Subsequence
- Leetcode: Arithmetic Slices II - SubsequenceLeetCode
- Leetcode 329. Longest Increasing Path in a MatrixLeetCode
- LintCode 主元素 II
- LintCode-BackPack II
- LintCode-Longest Common Substring
- LintCode-Maximum Subarray II
- LintCode-Word Search II
- LintCode-Majority Number II
- LintCode-Median II
- LintCode-Sort Colors II
- LintCode-Unique Path II
- Leetcode 329. Longest Increasing Path in a Matrix (python+cpp)LeetCodePython
- LintCode-Search 2D Matrix II
- LintCode 尋找旋轉排序陣列中的最小值 II排序陣列
- LintCode 刪除排序連結串列中的重複數字 II排序
- LeetCode #392: Is SubsequenceLeetCode
- Algorithm for Maximum Subsequence Sum zGo
- 《Continuous Integration》讀書筆記筆記
- leetcode392. Is SubsequenceLeetCode
- [atcoder 349] [F - Subsequence LCM]
- E. Increasing Subsequences__2
- influxdb 筆記: Continuous Queries - CQsUX筆記
- ACM Longest Repeated SequenceACM
- 領釦LintCode演算法問題答案-1354. 楊輝三角形II演算法
- Interview-Increasing Sequence with Length 3.View
- LeetCode-Wiggle SubsequenceLeetCode
- CF1922E Increasing Subsequences
- [LeetCode] 523. Continuous Subarray SumLeetCode
- [LeetCode] 727. Minimum Window SubsequenceLeetCode