给定一个推送序列,找到所有可能的弹出序列

问题描述

例如推送顺序为:1,2,3,所有可能的弹出顺序如下:

  • 1,3
  • 1,3,2
  • 2,1,3
  • 2,1
  • 3,1

我在互联网上找到了一种算法,(Java)代码是:

    public static void getAllPopSeq(List<Integer> pushSeq,int n,Deque<Integer> stack,List<Integer> popSeq,List<List<Integer>> res) {

        if (n == pushSeq.size() && stack.isEmpty()) {
            res.add(popSeq);
            return;
        } else {
            Deque<Integer> aux1 = new LinkedList<>(stack);
            Deque<Integer> aux2 = new LinkedList<>(stack);
            if (n < pushSeq.size()) {
                aux1.push(pushSeq.get(n));
                getAllPopSeq(pushSeq,n + 1,aux1,new ArrayList<>(popSeq),res);
            }
            if (!aux2.isEmpty()) {
                popSeq.add(aux2.pop());
                getAllPopSeq(pushSeq,n,aux2,res);
            }
        }
    }

但是我真的很难理解这个算法,如果有人可以帮我解释它,那将真的很有帮助。

或者您有其他解决方案,可以在此处发布。

谢谢!

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)