深搜啪的一下就完事了。
一开始想用广搜,后来发现还得自定义class,太麻烦了。
class Solution {
public List<List<Integer>> allPathsSourceTarget(int[][] graph) {
final List<List<Integer>> ans = new LinkedList<>();
final Deque<Integer> list = new LinkedList<>();
int aim = graph.length - 1;
list.add(0);
dfs(0, aim, graph, list, ans);
return ans;
}
void dfs(int now, int aim, int[][] graph, Deque<Integer> list, List<List<Integer>> ans) {
if(now == aim) {
ans.add(new LinkedList<>(list));
return;
}
for (int i : graph[now]) {
list.add(i);
dfs(i, aim, graph, list, ans);
list.removeLast();
}
}
}