文章目录
题目
思路
经典DFS深搜+回溯算法,模板题目。
以0节点为起点,递归所有可以从0节点出发到达的节点,在递归的同时把路径节点保存到 tmp 中,如果到达的节点为题目要求的最后一个节点,则把 tmp 添加到 答案 res 中。
代码实现(Java)
class Solution {
public List<List<Integer>> allPathsSourceTarget(int[][] graph) {
int n = graph.length;
List<List<Integer>> res = new LinkedList<List<Integer>>();
List<Integer> tmp = new LinkedList<Integer>();
tmp.add(0); //先将 0 起点节点加入到 tmp ,这样子每一个 不同的路径的起点都是 0
dfs(graph,n,res,tmp,0);
return res;
}
public void dfs(int[][] graph,int n,List<List<Integer>> res, List<Integer> tmp,int index) {
if(index == n-1) {
res.add(new LinkedList<Integer>(tmp));
return;
}
for(int i = 0; i<graph[index].length; i++) {
tmp.add(graph[index][i]);
dfs(graph,n,res,tmp,graph[index][i]);
tmp.remove(tmp.size()-1);
}
}
}
踩坑记录
回溯的代码为 tmp.remove(tmp.size()-1) , 调用的是 List 中的 remove 方法,通过查看源码,发现 remove 方法中的参数是 要移除的下标值或者是对象。本题中,我错把要移除的int值当成对象传入,导致一直报错内存超限,正确的做法是给 remove 方法传入集合长度的值-1,这是正确的下标值。
坚持分享,坚持原创,喜欢博主的靓仔靓女们可以看看博主的首页博客!
您的点赞与收藏是我分享博客的最大赞赏!
博主博客地址: https://blog.csdn.net/weixin_43967679
后记
祝各位能够拥有一个美好的五一假期,多陪陪家里人,女朋友!😄😄