Loading

给定入栈序列,求所有可能出栈结果

给定入栈序列,求所有可能出栈结果

这是一道招银网络的笔试题。
考试的时候有点懵逼,不知怎么这就死循环了;。Orz,挺简单的一道题目,一紧张可能就写不出来了。

// 输入序列
4 
1 2 3 4
//所有输出结果,按字典序进行排列;
1 2 3 4,1 2 4 3,1 3 2 4
1 3 4 2,1 4 4 3,2 1 3 4
2 1 4 3,2 3 1 4,2 3 4 1
2 4 4 3,3 4 2 4,3 4 4 2
3 4 4 4,4 4 4 3

具体的代码实现: 我采用了回溯思想;


package zhaoying;

import java.util.*;

public class Chuzhan {
    static List<List<Integer>> ans = new ArrayList<List<Integer>>() ;
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        while(scan.hasNext()) {
            int n = scan.nextInt();
            int[] arr = new int[n];
            for(int i = 0; i < n; i++){
                arr[i] = scan.nextInt();
            }

            LinkedList<Integer> stack = new LinkedList<>();
            LinkedList<Integer> output = new LinkedList<>();
            dfs(arr,0, stack, output);
            for(int i = 0; i < ans.size(); i++){
                System.out.print(ans.get(i).get(0));

                for(int j = 1; j < ans.get(i).size(); j++){

                    System.out.print(" " + ans.get(i).get(j));
                }
                
                if(i % 3 == 2)
                    System.out.println();
                else{
                    if(i != ans.size()-1){
                        System.out.print(',');
                    }

                }
            }
        }
    }

    static void dfs(int[] arr, int index, LinkedList<Integer> stack, LinkedList<Integer> output){
        if(index == arr.length && stack.size() == 0){
            ans.add(new ArrayList<>(output));
        }
        // 使用回溯法
        // 选择出栈:
            // 如果能出栈就出栈(这样的效果是:先出栈的拍前面)
        if(!stack.isEmpty()){
            int v = stack.pop();
            output.addLast(v);
            dfs(arr, index, stack, output);
            stack.addLast(v);
            output.removeLast();
        }
        // 选择入栈:
        if(index < arr.length){
            stack.push(arr[index]);
            dfs(arr, index + 1, stack, output);
            stack.pop();
        }
    }
}



posted @ 2020-09-25 20:35  Sidewinder  阅读(264)  评论(0编辑  收藏  举报