题解 | #火车进站#

火车进站

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

import java.util.Scanner;
import java.util.*;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    static List<String> res = new ArrayList<>();

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        // 注意 hasNext 和 hasNextLine 的区别
        int n = in.nextInt();
        int[] arr = new int[n];
        for (int i = 0; i < n; i++) {
            arr[i] = in.nextInt();
        }
        String sb = new String("");
        Stack<Integer> stk = new Stack<>();
        dfs(sb, 0, arr, stk, 0);
        Collections.sort(res);
        for (String str : res) {
            System.out.println(str);
        }

    }


    public static void dfs (String s, int n, int[] arr, Stack<Integer> stk, int i) {
        if (n == arr.length) res.add(s);

        else {
            if (!stk.empty()) {
                int tmp = stk.pop();
                dfs(s + tmp + " ", n + 1, arr, stk, i);
                stk.push(tmp);
            }

            if (i < arr.length) {
                stk.push(arr[i]);
                dfs(s, n, arr, stk, i + 1);
                stk.pop();
            }
        }

    }
}


全部评论

相关推荐

迷茫的大四🐶:好一个误闯天家,我也想闯一闯
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

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