题解 | #火车进站#

火车进站

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

import java.util.*;
public class Main{

    static int[] train;
    static String res;

    public static void main(String[] args){
        Scanner in = new Scanner(System.in);
        while(in.hasNextInt()){
            int n = in.nextInt();
            train = new int[n];
            res = new String();
            for(int i=0; i<n; i++){
                train[i] = in.nextInt();
            }
            List<String> list = new ArrayList<>();
            Stack<Integer> stack = new Stack<>();
            out(stack, 0, n, list);
            Collections.sort(list, new Comparator<String>() {
                @Override
                public int compare(String s1, String s2) {
                    return s1.compareTo(s2);
                }
            });
            Iterator<String> it = list.listIterator();
            while(it.hasNext()){
                System.out.println(it.next());
            }
        }
    }

    public static void out(Stack<Integer> stack, int index, int n, List<String> list){
        if(index == n&&stack.isEmpty()){
            list.add(new String(res));
            return;
        }
        if(stack.isEmpty()){
            stack.push(train[index++]);
            out(stack, index, n, list);
            stack.pop();
        }else{
            int temp = stack.pop();
            res += temp + " ";
            out(stack, index, n, list);
            res = res.substring(0, res.length()-2);
            stack.push(temp);
            if(index < n){
                stack.push(train[index++]);
                out(stack, index, n, list);
                stack.pop();
            }

        }
    }
}
全部评论

相关推荐

点赞 评论 收藏
分享
每晚夜里独自颤抖:要求太多的没必要理
点赞 评论 收藏
分享
陆续:不可思议 竟然没那就话 那就我来吧 :你是我在牛客见到的最美的女孩
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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