zoukankan      html  css  js  c++  java
  • 求入栈顺序为1234……N的序列的所有可能的出栈序列


    class Program
    {
        private static void Fun(int x, int n, Stack<int> stack, List<int> outList,ref int count)
        {
            if (outList.Count == n)
            {
                count++;
                Console.WriteLine(string.Join(',', outList));
            }
    
            if (x <= n)
            {
                stack.Push(x);
                Fun(x + 1, n, stack, outList, ref count);
                stack.Pop();
            }
    
            if(stack.Count > 0)
            {
                var temp = stack.Peek();
    
                stack.Pop();
                outList.Add(temp);
    
                Fun(x, n, stack, outList, ref count);
    
                stack.Push(temp);
                outList.RemoveAt(outList.Count - 1);
            }
        }
    
        static void Main(string[] args)
        {
            int n;
            string nStr;
            while (true)
            {
                while (true)
                {
                    Console.WriteLine("输入一个正整数:");
                    nStr = Console.ReadLine();
                    if (int.TryParse(nStr, out n))
                    {
                        break;
                    }
                }
    
                var stack = new Stack<int>();
                var outList = new List<int>();
                int count = 0;
                Fun(1, n, stack, outList, ref count);
                Console.WriteLine($"总计{count}种出栈方式。");
            }
        }
    }
    

  • 相关阅读:
    Swap Nodes in Pairs
    Permutations(copy)
    Sort Colors
    Merge Two Sorted Lists
    Implement Queue using Stacks
    Best Time to Buy and Sell Stock
    Happy Number
    Gray Code
    springMVC初次搭建,产生错误
    JSP常用指令
  • 原文地址:https://www.cnblogs.com/wj033/p/9124249.html
Copyright © 2011-2022 走看看