java - 如何找到列表的所有路径?
问题描述
我有一个这样的列表:
[[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
}
推荐阅读
- python - 如何使用 numpy 重写
- javascript - 将内联 javascript 转换为外部文件
- mysql - 如何在 mysql 5.7 中使用 sum over partition (withhout window function)
- php - 如何在 PHP 中的新 Amazon Alexa.com Rank API 中设置凭据?
- ruby - 如果类方法被覆盖,则访问类
- python - Pandas - 写实木复合地板并将列保持为十进制
- c# - 将数据从 XML 添加到组合框的 C# 问题
- macos - 如何安排脚本作业(macos)
- html - 单击复选框后突出显示标签项
- mongoose - 与 Mongoose Schema 关联的 Multer GridFS 存储文件上传