LintCode 398. Longest Continuous Increasing Subsequence II (DFS搜索经典题)

本文介绍了一种在二维矩阵中寻找最长连续递增子序列的算法,采用深度优先搜索(DFS)结合记忆化搜索的方法,可在O(nm)时间和内存复杂度下解决问题。示例代码展示了如何遍历矩阵并更新最长递增子序列长度。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  1. 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+记忆化搜索
注意:

  1. f[x][y] = max(f[x][y], f[newX][newY] + 1);
    这里不能简单的用f[x][y] = f[newX][newY] + 1。因为可能会覆盖一个之前另一个方向的更好的结果。
  2. 如果遇到一个节点已经访问过,则直接返回。因为可以直接利用该节点的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;
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值