zoukankan      html  css  js  c++  java
  • 元素和为目标值的子矩阵数量

    主要的解题思想,以下的题目虽然和本题有点不同,但主要的解题思想是一模一样的。

    该题的代码:

    import java.util.HashMap;
    import java.util.Map;
    
    class Solution {
        public int numSubmatrixSumTarget(int[][] matrix, int target) {
            int count = 0;
            int xlen = matrix.length;
            int ylen = matrix[0].length;
            for(int i=0;i<xlen;i++){
                for(int j=0;j<ylen;j++){
                    if(i==0&&j==0){
                       
                    }else if(i==0){
                        matrix[0][j] = matrix[0][j-1] + matrix[0][j];
                    }else if(j==0){
                        matrix[i][0] = matrix[i-1][0] + matrix[i][0]; 
                    }else{
                        matrix[i][j] = matrix[i-1][j] + matrix[i][j-1] + matrix[i][j] - matrix[i-1][j-1];   
                    }
                }
            }
            Map<Integer,Integer> map = new HashMap<>();
            int cha = 0;
            Integer t = 0;
            Integer s = 0;
            for(int step = 0;step<ylen;step++){
                //这里的step指的是,每次遍历(ylen==step+1)的所有的子矩形;第一次遍历ylen=1的所有的子矩形,第二次遍历ylen=2的所有的子矩形,... 
                for(int j=step;j<ylen;j++){
                    map.clear();
                    map.put(0,1);
                    for(int i=0;i<xlen;i++){
                        if(step == 0){
                            cha = matrix[i][j];
                        }else{
                            cha = matrix[i][j] - matrix[i][j-step];
                        }
                        t = map.get(cha);
                        s = map.get(cha-target);
                        if(t!=null){
                           map.put(cha,++t);
                        }else{
                           map.put(cha,1); 
                        }
                        if(s!=null){
                            count += s;
                        }
                    }
                }
            }
            return count;
        }
    }
  • 相关阅读:
    LVM磁盘逻辑卷扩容
    confluence 搭建总结
    GTX1050ti安装tensorflow2.0(gpu)
    sublime text 配置 markdown和预览
    Python 程序打包成 exe 可执行文件
    devc++ 配置openCV
    Ubuntu安装sublime text3
    sublime text 配置Miniconda编译环境
    sublime text 配置devc++ 编译环境
    2013-03-27 problem2 A Famous ICPC Team
  • 原文地址:https://www.cnblogs.com/erdanyang/p/11057452.html
Copyright © 2011-2022 走看看