问题:
难度: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);
}
}
}