zoukankan      html  css  js  c++  java
  • [LintCode] Longest Increasing Continuous subsequence II

    http://www.lintcode.com/en/problem/longest-increasing-continuous-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]
    ]
    
    这道题使用dfs+dp,在dfs时更新状态,状态转移方程为 dp[(i,j)] = max(dp[(smaller neibors of all)])  + 1,来看代码:
    class Solution {
    public:
        /**
         * @param A an integer matrix
         * @return an integer
         */
        int longestIncreasingContinuousSubsequenceII(vector<vector<int>>& A) {
            if (A.empty() || A[0].empty()) {
                return 0;
            } 
            
            int ret = 0;
            int maxRow = A.size();
            int maxCol = A[0].size();
            vector<vector<int>> dp(maxRow, vector<int>(maxCol));
            for (int i = 0; i < maxRow; i++) {
                for (int j = 0; j < maxCol; j++) {
                    ret = max(ret, dfs(i, j, maxRow, maxCol, A, dp));
                }
            }
            
            return ret;
        }
        
    private:
        int dfs(int i, int j, int maxRow, int maxCol,
                 const vector<vector<int>> &A,
                 vector<vector<int>> &dp) {
            // 记忆化搜索,如果有值(之前dfs已经计算出的)直接返回,不再计算 
            if (dp[i][j] != 0) {
                return dp[i][j];
            }
            
            // 从up开始顺时针
            const int dx[] = {0, 1, 0, -1};
            const int dy[] = {-1, 0, 1, 0};
            
            // dfs更新dp状态
            for (int ix = 0; ix < 4; ix++) {
                int x = i + dx[ix];
                int y = j + dy[ix];
                if (0 <= x && x < maxRow && 0 <= y && y < maxCol && A[i][j] < A[x][y]) {
                    dp[i][j] = max(dp[i][j], dfs(x, y, maxRow, maxCol, A, dp));
                } 
            }
            
            return ++dp[i][j];
        }
    };
  • 相关阅读:
    PowerDesigner执行SQL生成模型
    IBM,ORACLE 文档
    JAAS 自定义登陆模块
    JAAS 使用windos登陆示例
    IFRAME跨域
    JAVA RSA 数字签名
    JAVA数字证书
    搭模型时常用的numpy公式,不定时更新~
    Failed to connect to github.com port 443: Timed out
    linux和colab上安装torch_geometric踩坑记录,安装过程
  • 原文地址:https://www.cnblogs.com/jianxinzhou/p/4530825.html
Copyright © 2011-2022 走看看