qq_486412098 2015-12-24 04:27 采纳率: 50%
浏览 1297
已采纳

C# 两个孩子,一个孩子将a b c d 4个球放入一个只有一端开放的细管子里

C# 两个孩子,一个孩子将a b c d 4个球放入一个只有一端开放的细管子里
输出所有顺序

  • 写回答

4条回答 默认 最新

  • threenewbee 2015-12-24 05:22
    关注
     using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace ConsoleApplication1
    {
        class Program
        {
            static IEnumerable<string> foo(string seed, int max)
            {
                if (seed.Count(x => x == '+') == max && seed.Count(x => x == '-') == max)
                    yield return seed;
                if (seed.Count(x => x == '+') > seed.Count(x => x == '-'))
                    foreach (string s in foo(seed + "-", max))
                        yield return s;
                if (seed.Count(x => x == '+') <= max)
                    foreach (string s in foo(seed + "+", max))
                        yield return s;
            }
    
            static void display(string s)
            {
                Console.Write(s + "\t");
                char c = 'a';
                Stack<char> st = new Stack<char>();
                foreach (char ch in s)
                {
                    if (ch == '+') st.Push(c++);
                    if (ch == '-') Console.Write(st.Pop());
                }
                Console.WriteLine();
            }
            static void Main(string[] args)
            {
                foreach (string s in foo("", 4)) display(s);
            }
        }
    }
    
    

    +-+-+-+- abcd
    +-+-++-- abdc
    +-++--+- acbd
    +-++-+-- acdb
    +-+++--- adcb
    ++--+-+- bacd
    ++--++-- badc
    ++-+--+- bcad
    ++-+-+-- bcda
    ++-++--- bdca
    +++---+- cbad
    +++--+-- cbda
    +++-+--- cdba
    ++++---- dcba
    Press any key to continue . . .

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?