有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

n个数组的组合使用Java从每个数组中选择一个元素

我在Geeksforgeks公司做这个算法练习:

Given a list of arrays (of any size, not limited to two arrays), find all combinations where each combination contains one element from each given array.

Examples:

Input:

[[1, 2], [3, 4]]

Output:

1 3
1 4
2 3
2 4

我试图用这种方法自己解决它:

Initialize "result" list of arraylist.
For each element of the first array in the input list:
   depth = 1
   while(depth < list.size())
    arrayToCombineWithItsElmt = list.get(depth)
    for(int i = 0; i < arrayToCombineWithItsElmt.size(); i++)
      GenerateCombinations(result, arrayToCombineWithItsElmt(i))
    depth++
return result

generateCombinations(List<ArrayList> result, int element) method should:

  1. copy result list (which contains previous combinations)
  2. remove all elements of result list
  3. iterate over the copied list and for each Array add the element
  4. Add the array to result list.

我没有使用Java编写(代码),因为我觉得它不正确(解决问题的方法非常复杂)。 从这个蛮力算法,我在尝试手动解决一个例子后得到的,如何优化


共 (0) 个答案