链接:https://leetcode-cn.com/problems/all-paths-from-source-to-target/
回溯法枚举
java代码:
class Solution {
List<List<Integer>> ans = new ArrayList();
List<Integer>temp = new ArrayList();
public List<List<Integer>> allPathsSourceTarget(int[][] graph) {
temp.add(0);
backtrack(graph,0);
return ans;
}
private void backtrack(int [][]graph,int begin)
{
if(begin==graph.length-1)
{
ans.add(new ArrayList(temp));
return;
}
for(int i = 0;i<graph[begin].length;i++)
{
temp.add(graph[begin][i]);
backtrack(graph,graph[begin][i]);
temp.remove(temp.size()-1);
}
}
}