- Longest Continuous Increasing Subsequence II
Give you an integer matrix (with row size n, column size m),find the longest increasing continuous subsequence in this matrix. (The definition of the longest increasing continuous subsequence here can start at any row or column and go up/down/right/left any direction).
Example
Given a matrix:
[
[1 ,2 ,3 ,4 ,5],
[16,17,24,23,6],
[15,18,25,22,7],
[14,19,20,21,8],
[13,12,11,10,9]
]
return 25
Challenge
O(nm) time and memory.
思路:DFS+记忆化搜索
注意:
- f[x][y] = max(f[x][y], f[newX][newY] + 1);
这里不能简单的用f[x][y] = f[newX][newY] + 1。因为可能会覆盖一个之前另一个方向的更好的结果。 - 如果遇到一个节点已经访问过,则直接返回。因为可以直接利用该节点的f值。
代码如下:
class Solution {
public:
/**
* @param matrix: A 2D-array of integers
* @return: an integer
*/
int longestContinuousIncreasingSubsequence2(vector<vector<int>> &matrix) {
const int n = matrix.size();
if (n == 0) return 0;
const int m = matrix[0].size();
f.resize(n, vector<int>(m, 1));
visited.resize(n, vector<bool>(m, false));
gMaxLen = 1;
for (int i = 0; i < n; ++i) {
for (int j = 0; j < m; ++j) {
helper(matrix, i, j);
gMaxLen = max(gMaxLen, f[i][j]);
}
}
return gMaxLen;
}
private:
void helper(vector<vector<int>> &matrix, int x, int y) {
vector<int> dirX = {1, -1, 0, 0};
vector<int> dirY = {0, 0, 1, -1};
const int n = matrix.size();
const int m = matrix[0].size();
if (!visited[x][y]) {
visited[x][y] = true;
for (int i = 0; i < 4; ++i) {
int newX = x + dirX[i];
int newY = y + dirY[i];
if ((newX >= 0) && (newX < n) && (newY >= 0) && (newY < m)) {
if (matrix[newX][newY] > matrix[x][y]) {
helper(matrix, newX, newY);
f[x][y] = max(f[x][y], f[newX][newY] + 1);
}
}
}
}
}
int gMaxLen;
vector<vector<int>> f;
vector<vector<bool>> visited;
};
本文介绍了一种在二维矩阵中寻找最长连续递增子序列的算法,采用深度优先搜索(DFS)结合记忆化搜索的方法,可在O(nm)时间和内存复杂度下解决问题。示例代码展示了如何遍历矩阵并更新最长递增子序列长度。
5万+

被折叠的 条评论
为什么被折叠?



