一、Problem
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 upper, lower 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.
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.
二、Solution
方法一:贪心构造
唉,还是不是很会写这种构造题,遇到分类讨论就想得很慢,生怕少分析一种情况,这里就是卡在返回空列表的那一种情况,但分类讨论的思想还是正确的:
- colsum[i] 为 2 时,不用想了,第 i 列都是 2
- colsum[i] 为 1 时,这个要小心,因为有两行,所以我们要规定一个顺序,即遇到 1 时,1 先加到哪一行中。
- colsum[i] 为 0 时,也不用想,第 i 列全是 0
class Solution {
public List<List<Integer>> reconstructMatrix(int up, int lo, int[] cs) {
int n = cs.length, tot = 0;
for (int i = 0; i < n; i++) {
if (cs[i] == 2) {
up--; lo--;
} else if (cs[i] == 1)
tot++;
}
List<List<Integer>> ans = new LinkedList<>();
if (up + lo != tot || up < 0 || lo < 0)
return ans;
List<Integer> u = new LinkedList<>(), l = new LinkedList<>();
for (int i = 0; i < n; i++) {
if (cs[i] == 2) {
u.add(1); l.add(1);
} else if (cs[i] == 1) {
if (up-- > 0) {
u.add(1);
l.add(0);
} else if (lo-- > 0) {
u.add(0);
l.add(1);
}
} else {
u.add(0); l.add(0);
}
}
ans.add(u);
ans.add(l);
return ans;
}
}
复杂度分析
- 时间复杂度:,
- 空间复杂度:,