[LintCode] Longest Increasing Continuous subsequence II

本文探讨了在给定的二维整数矩阵中寻找最长递增连续子序列的问题,提供了详细的算法实现,包括动态规划方法和深度优先搜索策略,旨在帮助读者理解并解决此类问题。

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

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.

 

备忘录,dp[i][j] = max{dp[i-1][j], dp[i][j-1], dp[i+1][j], dp[i][j+1]} + 1。

 1 class Solution {
 2 public:
 3     /**
 4      * @param A an integer matrix
 5      * @return  an integer
 6      */
 7     bool isValid(vector<vector<int>> &A, int x, int y) {
 8         return x >= 0 && x < A.size() && y >= 0 && y < A[0].size();
 9     }
10     int dfs(vector<vector<int>> &A, vector<vector<int>> &dp, int x, int y) {
11         if (dp[x][y] != -1) return dp[x][y];
12         const int dx[4] = {0, 1, 0, -1};
13         const int dy[4] = {1, 0, -1, 0};
14         int tmp = 1;
15         for (int i = 0; i < 4; ++i) {
16             int xx = x + dx[i], yy = y + dy[i];
17             if (isValid(A, xx, yy) && A[x][y] > A[xx][yy]) tmp = max(tmp, dfs(A, dp, xx, yy) + 1);
18         }
19         dp[x][y] = tmp;
20         return dp[x][y];
21     }
22     int longestIncreasingContinuousSubsequenceII(vector<vector<int>>& A) {
23         // Write your code here
24         if (A.empty() || A[0].empty()) return 0;
25         int res = 0;
26         vector<vector<int>> dp(A.size(), vector<int>(A[0].size(), -1));
27         for (int i = 0; i < A.size(); ++i) {
28             for (int j = 0; j < A[0].size(); ++j) {
29                 res = max(res, dfs(A, dp, i, j));
30             }
31         }
32         return res;
33     }
34 };

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值