火车进站,华为

import java.util.*;
public class Main {
    static List<String> res;
    static Stack<Integer> stk;
    static void dfs(int[] a, int n, int u, String path, int times) {
        if(times == n) {
            res.add(path);
            return;
        }
        if(!stk.isEmpty()) { // 出站
            int t = stk.pop();
            dfs(a, n, u, path + t + " ", times+1);
            stk.push(t);
        }
        if(n == u) return;
        stk.push(a[u]);
        dfs(a, n, u+1, path, times);
        stk.pop();
    }
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        while(sc.hasNext()) {
            int n = sc.nextInt();
            int[] a = new int[n];
            for(int i=0; i < n; i++) 
                a[i] = sc.nextInt();
            res = new ArrayList<>();
            stk = new Stack<>();
            dfs(a, n, 0, "", 0);
            Collections.sort(res);
            for(int i=0; i < res.size(); i++) {
                System.out.println(res.get(i));
            }
        }
    }
}

posted @ 2020-07-06 19:15  li修远  阅读(112)  评论(0编辑  收藏  举报