LeetCode не совпадает ответ
В общем, суть проблемы такова, пытаюсь решить задачу на leetcode, вроде бы решил, отправил. Говорит. что вывод не соответсвует тому, что он ожидает. Запускаю свой код с теми же входными данными у себя локально, и вывод уже такой, какой должен быть и там.
Текст задачи
Given a directed acyclic graph (DAG) of n nodes labeled from 0 to n - 1, find all possible paths from node 0 to node n - 1, and return them in any order. The graph is given as follows: graph[i] is a list of all nodes you can visit from node i (i.e., there is a directed edge from node i to node graph[i][j]).
static List<List<Integer>> answer = new ArrayList<>();
List<Integer> currentPath = new ArrayList<>();
public static void main(String[] args) {
int[][] graph = new int[][] {
{4, 3, 1},
{3, 2, 4},
{3},
{4},
{}
};
Solution797 solution797 = new Solution797();
var result = solution797.allPathsSourceTarget(graph);
System.out.println(result);
}
public List<List<Integer>> allPathsSourceTarget(int[][] graph) {
getPaths(0, graph);
return answer;
}
public void getPaths(int currPos, int[][] graph) {
if (currentPath == null) {
currentPath = new ArrayList<>();
}
currentPath.add(currPos);
if (graph[currPos].length == 0) {
answer.add(new ArrayList<>(currentPath));
currentPath.remove((Integer) currPos);
return;
}
for (int i = 0; i < graph[currPos].length; i++) {
getPaths(graph[currPos][i], graph);
currentPath.remove((Integer) graph[currPos][i]);
}
}
Ответы (1 шт):
Что то в вашем коде явно работает не так, как надо. Я бы убрал все поля, как статические и не статические, так как ваш экземпляр класса может быть запущен на нескольких тестах, а вы в него состояние добавили.
Особенно вопросы возникают к статическим полям. Вот оно там зачем?
Вот этот мой код прошел все проверки без проблем
class Solution {
public List<List<Integer>> allPathsSourceTarget(int[][] graph) {
LinkedList<Integer> path = new LinkedList<>();
path.add(0);
List<List<Integer>> ret = new ArrayList<>();
getAllPaths(graph, path, graph.length - 1, ret);
return ret;
}
private void getAllPaths(int[][] graph, LinkedList<Integer> path, int target, List<List<Integer>> paths) {
int latest = path.getLast();
if (latest == target) {
List<Integer> ret = new ArrayList<>(path);
paths.add(ret);
return;
}
for (int n : graph[latest]) {
path.add(n);
getAllPaths(graph, path, target, paths);
path.removeLast();
}
}
}
Как видите, нет состояния в классе - нет и проблем с состоянием.

