主要的解題思想,如下的題目雖然和本題有點不一樣,但主要的解題思想是如出一轍的。java
該題的代碼:spa
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; } }