[Leetcode学习-java]All Paths From Source to Target(所有可达路径)

问题:

难度:medium

说明:

输入一个二维数组,然后二维数组每个元素都是记录到达下一个元素的索引,将所有能够达到 二维数组末尾元素的路径返回,可以无序。

问题链接:https://leetcode.com/problems/all-paths-from-source-to-target/

相关问题:

[Codewar训练]Permutations(String)(全排列):https://blog.csdn.net/qq_28033719/article/details/105860028

输入案例:

// 0 元素有 1 2,然后跳到 1 元素有 3,3 元素就是结尾了
// 以此类推
Example:
Input: [[1,2], [3], [3], []] 
Output: [[0,1,3],[0,2,3]] 
Explanation: The graph looks like this:
0--->1
|    |
v    v
2--->3
There are two paths: 0 -> 1 -> 3 and 0 -> 2 -> 3.

我的代码:

很简单,一边循环一般递归,和蛙跳一样的原理。

class Solution {
    public List<List<Integer>> allPathsSourceTarget(int[][] graph) {
        List<List<Integer>> res = new ArrayList<List<Integer>>();
        helper(graph, 0, new int[graph.length], 0, res);
        return res;
    }
    
    public void helper(int[][] g, int index, int[] queue, int end, List<List<Integer>> res) {
        // 如果发现到达了结尾,就加入
        if(index == g.length - 1) {
            List<Integer> list = new ArrayList();
            list.add(0);
            for(int i = 0;i < end;i ++) list.add(queue[i]);
            res.add(list);
            return;
        }
        int[] temp = g[index];
        // 一边循环,一边递归
        for(int i = 0;i < temp.length;i ++) {
            queue[end] = temp[i];
            helper(g, temp[i], queue, end + 1, res);
        }
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值