题目
https://leetcode.com/problems/all-paths-from-source-to-target/
Given a directed, acyclic graph of N nodes. Find all possible paths from node 0 to node N-1, and return them in any order.
The graph is given as follows: the nodes are 0, 1, ..., graph.length - 1. graph[i] is a list of all nodes j for which the edge (i, j) exists.
Example:
Input: [[1,2], [3], [3], []]
Output: [[0,1,3],[0,2,3]]
Explanation: The graph looks like this:
0--->1
| |
v v
2--->3
There are two paths: 0 -> 1 -> 3 and 0 -> 2 -> 3.
Note:
The number of nodes in the graph will be in the range [2, 15].
You can print different paths in any order, but you should keep the order of nodes inside one path.
解答
一开始也没看懂题意,这个二维数组是如何描述这个有向图。其实是这样的,二维数组的长度就是节点的个数,比如示例中的长度为4,所以节点分为是0, 1, 2, 3。
然而,下一维度描述了,当前第i个节点指向哪个节点。
比如,graph[0]是[1, 2],他的意思是,0号节点指向1,2
class P797_All_Paths_From_Source_to_Target {
// 把结果集弄成静态变量,省的传来传去
static List<List<Integer>> result = new ArrayList<>();
public List<List<Integer>> allPathsSourceTarget(int[][] graph) {
List<Integer> path = new ArrayList<>();
result.clear();
helper(0, graph, path);
return result;
}
public static void helper(int curr, int[][] graph, List<Integer> path) {
// 将当前节点加入路径
path.add(curr);
// 查一下当前节点的邻接表,如果长度为0,所以到头了,把这条路径加入结果集
if (graph[curr].length == 0) {
result.add(path);
} else {
// 如果没有到头,那么查邻接表,每一个都取出来进行递归。
for (int n : graph[curr]) {
// 这里要注意克隆了一下路径数组,不然的话,都加到一个里面去了……
helper(n, graph, clone(path));
}
}
}
public static List<Integer> clone(List<Integer> arr) {
return new ArrayList<>(arr);
}
}