HJ77 火车进站 | 题解

import java.util.*;

public class Main {
    public static List<String> res = new ArrayList<>();

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        while (in.hasNext()) {
            int n = in.nextInt();
            int[] nums = new int[n];
            Stack<Integer> stk = new Stack<>();
            for (int i = 0; i < n; i++) {
                nums[i] = in.nextInt();
            }
            helper(nums, 0, stk, "", 0);
            Collections.sort(res);
            for (String s : res) {
                System.out.println(s);
            }
        }
    }

    public static void helper(int[] nums, int i, Stack<Integer> stk, String s, int n) {
        if (n == nums.length)
            res.add(s);
        if (!stk.empty()) {
            int tmp = stk.pop();
            helper(nums, i, stk, s + tmp + " ", n +1);
            stk.push(tmp);
        }
        if (i < nums.length) {
            stk.push(nums[i]);
            helper(nums, i + 1, stk, s, n);
            stk.pop();
        }
    }
}

全部评论

相关推荐

不愿透露姓名的神秘牛友
07-07 18:05
哈哈哈哈哈感觉朋友找工作的已经疯掉了,直接上图
码农索隆:真老板娘:“我嘞个去,这不我当年的套路吗
点赞 评论 收藏
分享
06-12 16:00
天津大学 Java
牛客30236098...:腾讯坏事做尽,终面挂是最破防的 上次被挂了后我连简历都不刷了
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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