LeetCode--All Paths From Source to Target

思路:

    先按照数组顺序遍历索引,直到索引到达最后一个,添加索引,返回结果。以该方式递归,不断将之前的索引加入到每个path的开头,最后返回最终结果。

class Solution {
    public List<List<Integer>> allPathsSourceTarget(int[][] graph) {
        return helper(graph,0);
    }
    
    private List<List<Integer>> helper(int[][] graph,int pos){
        List<List<Integer>> res=new ArrayList();
        if(pos==graph.length-1){
            List path=new ArrayList<Integer>();
            path.add(pos);
            res.add(path);
            return res;
        }
        
        for(int n:graph[pos]){
            for(List<Integer> path:helper(graph,n)){
                path.add(0,pos);
                res.add(path);
            }
        }
        
        return res;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_21752135/article/details/79977390
今日推荐