class Solution {
public List<List<Integer>> allPathsSourceTarget(int[][] graph) {
//这一题需要我们列举出所有从0到n-1的所有路劲,解决这个问题需要多步,每一步有多个选择,又要列举出所有的情况,很明显这该使用回溯法
//至于回溯的参数,我们需要知道每一步遍历的是哪一个节点,和该节点的相邻节点有哪些,并且需要动态记录,所以至少需要有本节点,领接矩阵,动态数组,结果数组四个参数
List<Integer> path = new LinkedList<>();
List<List<Integer>> result = new LinkedList<>();
backcheck(0,graph,path,result);
return result;
}
private void backcheck(int cur,int[][] graph,List<Integer> path,List<List<Integer>> result){
//节点只有两种可能,一是末尾节点,二就是中间节点,对于末尾节点来说我们要处理的就是添加路劲,对于中间节点来说我们需要添加所有孩子
path.add(cur);
if(cur == graph.length - 1){
result.add(new LinkedList<>(path));
}else{
for(int next : graph[cur]){
backcheck(next,graph,path,result);
}
}
//回到前一个状态由其他节点继续遍历
path.remove(path.size() - 1);
}
}
所有路径java实现
最新推荐文章于 2022-12-22 11:48:32 发布