class Solution {
public List<List<Integer>> allPathsSourceTarget(int[][] graph) {
List<List<Integer>> res = new ArrayList<List<Integer>>();
List<Integer> path = new ArrayList<Integer>();
path.add(0);
helper(0, path, res, graph);
return res;
}
// 回溯算法求解
private void helper(int index, List<Integer> path, List<List<Integer>> res, int[][] graph) {
if (graph.length - 1 == index) {
res.add(new ArrayList<Integer>(path));
return;
}
int[] dresses = graph[index];
for (int i = 0; i < dresses.length; i++) {
path.add(dresses[i]);
helper(dresses[i], path, res, graph);
path.remove(path.size() - 1);
}
}
}
797. 所有可能的路径
最新推荐文章于 2024-05-25 10:45:36 发布