不重复矩阵的组合

时间:2014-11-18 14:35:42

标签: java algorithm matrix combinations

我有一个包含在二维数组中的矩阵。

int[][] combinationValues

这个数组的大小可能会有所不同,但是使用我现在的测试用例,它的最大大小是6乘6。

此矩阵是一组非不同的整数,示例值为......

[1][1,2,3]
[2][4,5,6]
[3][7,8,9]

我希望获得这些值的所有组合的数组/列表而不重复,每行只取一个值。因此,使用前面的示例值,结果将是......

[1,5,9] , [1,6,8] , [2,4,9] , [2,7,6] , [3,4,8] , [3,5,7]

因此以下结果不正确。

[1,4,7] //three from the first row
[1,5,8] //two from the second row

如果你可以帮助我,非常欢迎伪代码,但我目前正在使用Java来实现。

2 个答案:

答案 0 :(得分:1)

这是解决问题的基本思路:

  • 使用将存储所使用索引的数组(或其他集合)(重复
  • 0到最后可用的索引:
    • 检查索引是否已标记为重复
    • 如果它是重复的,则转到下一个索引
    • 如果它不重复,那么
      • 转到下一个可能的数组
      • 获取该索引的元素
      • 将索引添加到数组(或集合)以将其标记为 duplicate
      • 在可用数组的for中重复此相同过程
      • 删除数组(或集合)的索引,将其取消标记为重复

答案 1 :(得分:1)

所以你想按行和按列一个元素?简单的组合分析说你应该得到n!个解决方案。

您可以轻松地回溯java或任何其他可以动态附加到列表的语言

伪代码:

void test(List<List<Integer>> matrix, int row, int column, List<List<Integer>> results,
        List<Integer> current, List<Integer> used)
    // tries to add a new value to current result
    if used does not contain j {
        add matrix[i][j] to list current
        add j to list used
        if i is last row (i == matrix.size() -1) {
            add result to list results
        }
        else {         // processes next row
            for(int k=0, k<matrix[0].size(); k++) {
                test(matrix, i+1, k, results, current, used)
            }
        }
    }
}

主要代码:

List<List<Integer>> results = new ArrayList<List<Integer>>(); // initializes results
for (i=0; i<matrix[0].size(); i++) {  // try each element of first line
    test(matrix, 0, i, results, new ArrayList<Integer>(), new ArrayList<Integer>())
}
相关问题