图的介绍:https://labuladong.gitee.io/algo/2/18/26/
图类似多叉树
所有可能的路径
// (https://leetcode-cn.com/problems/all-paths-from-source-to-target/
// 回溯求解
class Solution {
List<List<Integer>> res = new LinkedList<>();
public List<List<Integer>> allPathsSourceTarget(int[][] graph) {
LinkedList<Integer> path = new LinkedList<>();
traverse(graph, 0, path);
return res;
}
void traverse(int[][] graph, int root, LinkedList<Integer> path) {
path.add(root);
// 跳出条件
int n = graph.length;
if (root == n - 1) {
res.add(new LinkedList<>(path));
path.removeLast();
return ;
}
// 遍历s
for (int point : graph[root]) {
traverse(graph, point, path);
}
path.removeLast();
}
}
Reference:
- https://labuladong.gitee.io/algo/