我的解决方案是,我们首先假设所有列都有 1,然后我们逐行遍历我们仍然拥有的可能解决方案,并切割不能成为解决方案的列。
此解决方案是用 Java 编写的:
解决方案 1:O(n^2) 直截了当
public class Main
{
// Given A: an M x N matrix
public static ArrayList<Integer> solve (Integer [][] matrix)
{
// Assuming all columns have 1s, we have list S
ArrayList<Integer> S = new ArrayList<Integer>();
// S = { 1, 2, .., N }
for (int i=0; i < matrix[0].length; i++)
{
S.add(i);
}
// For Row i: 1..M
for (Integer i = 0; i < matrix.length; i++)
{
// For Column j in list S
for (Integer j : S)
{
if (matrix[i][j] != 1)
{
S.remove(j);
}
}
}
return S;
}
public static void main (String [] args)
{
int [][] matrix =
{
{1,1,1},
{0,1,1},
{0,0,1},
};
ArrayList<Integer> columns = solve (matrix);
System.out.print(" columns that have 1s are: ");
for (Integer n : columns) System.out.print(n+" ");
}
}
解决方案 2:使用自定义数据结构的 O(n)
private class Column
{
public ArrayList<Integer> data;
public int count;
public Column ()
{
data = new ArrayList<Integer>();
count = 0;
}
public void add (int val)
{
data.add(val);
count += val;
}
}
public class Main
{
public static void main (String [] args)
{
Column [] matrix =
{
new Column (),
new Column (),
new Column ()
};
matrix[0].add(1);
matrix[0].add(0);
matrix[0].add(0);
matrix[1].add(1);
matrix[1].add(1);
matrix[1].add(0);
matrix[2].add(1);
matrix[2].add(1);
matrix[2].add(1);
System.out.print(" columns that have 1s are: ");
for (Column column : matrix)
{
if (column.count == column.data.size())
System.out.print(n+" ");
}
}
}