我有一个这样的列表:
[[A], [B, C, D], [E, F], [G]]
对于 Java 代码初始化:
List<List<String>> data = new ArrayList<>();
data.add(Arrays.asList("A"));
data.add(Arrays.asList("B", "C", "D"));
data.add(Arrays.asList("E", "F"));
data.add(Arrays.asList("G"));
并希望得到如下结果:
[[A,B,E,G],[A,B,F,G], [A,C,E,G],[A,C,F,G],[A,D,E,G],[A,D,F,G]]
怎么做?非常感谢。
最佳答案
你可以写一个递归算法来解决这个问题。对于每个递归调用,该算法在图中向下移动一层。它的要点是首先计算当前所在层下的所有路径,然后将当前层中的所有节点添加到这些路径。
这里有一些伪代码可以让你继续:
paths(input) {
if input is empty -> return empty // This is your base case
currentNodes = input[0]
subPaths = paths(input.tail) // Recursive call with the rest of your input
if subPaths is empty -> return input // The paths from the last layer is itself
result = emptyList()
for all nodes in currentNodes
for all paths in subPaths
prepend node to path and add to result
return result
}
关于java - 如何找到列表的所有路径?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55195012/