LeetCode - 1605. Find Valid Matrix Given Row and Column Sums

链接:https://leetcode-cn.com/problems/find-valid-matrix-given-row-and-column-sums/
难度:medium

解题思路:填矩阵,从每个单元格的最大可以填的数字开始,一次递减,然后回溯。不过看起来效率不是很高。

class Solution {
    public int[][] restoreMatrix(int[] rowSum, int[] colSum) {
        int[][]out = new int[rowSum.length][];
        for(int i = 0; i < rowSum.length; i ++) {
            out[i] = new int[colSum.length];
        }

        calc(out, 0, 0, rowSum, colSum);
        return out;
    }

    private boolean calc(int[][]out, int r, int c, int[] rs, int[] cs) {
        if(c >= cs.length) {
            c = 0;
            r ++;
        }
        if(r >= rs.length) {
            return true;
        }
        
        int rowSum = rs[r];
        int colSum = cs[c];

        int rowLeft = rowSum;
        int colLeft = colSum;
        
        // row
        for(int i = 0; i < cs.length; i ++) {
            if(i != c) {
                rowLeft -= out[r][i];
            }
        }

        // col
        for(int i = 0; i < rs.length; i ++) {
            if(i != r) {
                colLeft -= out[i][c];
            }
        }

        int min = Math.min(rowLeft, colLeft);
        while(min >= 0) {
            out[r][c] = min;
            boolean result = calc(out, r, c + 1, rs, cs);
            if(result) {
                return true;
            }
            out[r][c] = 0;
            min --;
        }
        return false;
    }

}

执行用时: 1567 ms , 在所有 Java 提交中击败了 5.03% 的用户
内存消耗: 85.1 MB , 在所有 Java 提交中击败了 5.06% 的用户

你可能感兴趣的:(LeetCode - 1605. Find Valid Matrix Given Row and Column Sums)