- 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;
};