题解 | 火车进站

火车进站

https://www.nowcoder.com/practice/97ba57c35e9f4749826dc3befaeae109

没想到这个不起眼的小题还挺费心的。

  1. 思路:模拟出入站(栈),并配合回溯。
  2. 两处回溯:进站,出栈(进path)
import java.util.*;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int n = Integer.parseInt(in.nextLine());
        String[] trains = in.nextLine().split(" ");
        Stack<String> stack = new Stack<>();
        List<List<String>> allPath = new ArrayList<>();
        backtrace(trains, 0, stack, new ArrayList<>(), allPath);
        List<String> allPathStr = new ArrayList<>();
        for (List<String> path : allPath) {
            allPathStr.add(String.join(" ", path));
        }
        allPathStr.sort((o1, o2) -> o1.compareTo(o2));
        for (String s : allPathStr) {
            System.out.println(s);
        }
    }

    public static void backtrace(String[] trains, int idx, Stack<String> stack,
                                 List<String> path, List<List<String>> allPath) {
        if (path.size() == trains.length) {
            allPath.add(new ArrayList<>(path));
            return;
        }
        // 还有火车没进栈的快进
        if (idx < trains.length) {
            stack.push(trains[idx]);
            backtrace(trains, idx + 1, stack, path, allPath);
            stack.pop(); // 回溯
        }
        if (!stack.isEmpty()) {
            // 出栈
            String popTrain = stack.pop();
            path.add(popTrain);
            backtrace(trains, idx, stack, path, allPath);
            // 再次回溯
            path.remove(path.size() - 1);
            stack.push(popTrain);
        }
    }
}


常规算法题目专栏 文章被收录于专栏

这里记录一些常规的算法题目题解,主要包括中等难度,还有一些有意思的题目~

全部评论
思路清晰
点赞 回复 分享
发布于 04-02 23:21 上海

相关推荐

02-28 13:25
已编辑
门头沟学院 Java
点赞 评论 收藏
分享
评论
2
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务