[LeetCode] 1253. Reconstruct a 2-Row Binary Matrix 重構 2 行二進制矩陣



Given the following details of a matrix with n columns and 2 rows :

  • The matrix is a binary matrix, which means each element in the matrix can be 0 or 1.
  • The sum of elements of the 0-th(upper) row is given as upper.
  • The sum of elements of the 1-st(lower) row is given as lower.
  • The sum of elements in the i-th column(0-indexed) is colsum[i], where colsum is given as an integer array with length n.

Your task is to reconstruct the matrix with upperlower and colsum.

Return it as a 2-D integer array.

If there are more than one valid solution, any of them will be accepted.

If no valid solution exists, return an empty 2-D array.

Example 1:

Input: upper = 2, lower = 1, colsum = [1,1,1]
Output: [[1,1,0],[0,0,1]]
Explanation: [[1,0,1],[0,1,0]], and [[0,1,1],[1,0,0]] are also correct answers.

Example 2:

Input: upper = 2, lower = 3, colsum = [2,2,1,1]
Output: []

Example 3:

Input: upper = 5, lower = 5, colsum = [2,1,2,0,1,0,1,2,0,1]
Output: [[1,1,1,0,1,0,0,1,0,0],[1,0,1,0,0,0,1,1,0,1]]

Constraints:

  • 1 <= colsum.length <= 10^5
  • 0 <= upper, lower <= colsum.length
  • 0 <= colsum[i] <= 2

這道題說是有一個 2 by n 的數組,且只含有0和1兩個數字,現在知道第一行的數字和為 upper,第二行的數字和為 lower,且各列的數字和在數組 colsum 中,現在讓重建這個數組,若無法重建,則返回空數組。由於原數組中只有0和1,而且只有兩行,則每一列的和只有三種情況,0,1,和2。其中0和2的情況最簡單,上下兩個位置分別只能為0和1,只有當列和為1的時候,才會有不確定性,不知道到底是上面的數字為1還是下面的數字為1。這個時候其實可以使用貪婪算法的思想,判斷的依據是此時的 upper 和 lower 的值,當 upper 大於 lower 時,就讓上面的數字為1,否則就讓下面的數字為1。

這種貪婪算法可以在有解的情況下得到一個合法解,因為這道題沒有讓返回所有的合法的解。明白了思路,代碼就不難寫了,遍歷每一列,先更新上位數字,若當前列之和為2,則上位數字一定是1,或者列之和為1,且 uppper 大於 lower 的時候,上位數字也是1。再來更新下位數字,若當前列之和為2,則下位數字一定是1,或者列之和為1,且此時上位數字是0的話,則下位數字是1。最后別忘了 upper 和 lower 分別減去當前的上位和下位數字。最后返回的時候判斷,若 upper 和 lower 同時為0了,則返回 res,否則返回空數組即可,參見代碼如下:


class Solution {
public:
    vector<vector<int>> reconstructMatrix(int upper, int lower, vector<int>& colsum) {
        vector<vector<int>> res(2, vector<int>(colsum.size()));
        for (int i = 0; i < colsum.size(); ++i) {
            res[0][i] = colsum[i] == 2 || (colsum[i] == 1 && upper > lower);
            res[1][i] = colsum[i] == 2 || (colsum[i] == 1 && !res[0][i]);
            upper -= res[0][i];
            lower -= res[1][i];
        }
        return upper == 0 && lower == 0 ? res : vector<vector<int>>();
    }
};

Github 同步地址:

https://github.com/grandyang/leetcode/issues/1253


類似題目:

Find Valid Matrix Given Row and Column Sums


參考資料:

https://leetcode.com/problems/reconstruct-a-2-row-binary-matrix/

https://leetcode.com/problems/reconstruct-a-2-row-binary-matrix/discuss/425793/C%2B%2BJava-5-lines


LeetCode All in One 題目講解匯總(持續更新中...)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM