【问题标题】:Combinations Generation using Backtracking Algorithm使用回溯算法生成组合
【发布时间】:2023-03-29 21:37:02
【问题描述】:

我一直致力于使用回溯算法生成 3 个数字组合 到目前为止,我已经完成了以下工作:

        static int a, b, c;

    static void Combo(int a,int b, int c)
    {
        if (a != 10)
        {
            Combo(a, b, c);
            a++;

        }

            if (b != 10)
            {
                 Combo(a, b, c);
                b++;

            }


        if(c != 10)
        {
                    Combo(a,b,c);
            c++;

        }
        Console.WriteLine("( {0}, {1}, {2})",a,b,c);


    }

主要方法:

        static void Main(string[] args)
    {
        Console.WriteLine("Press Any Key to Start Generating xxx number Combination");
        Console.ReadKey();

        Combo(0,0,0);
        Console.WriteLine("Combo function has finished Successfully!");
        Console.ReadKey();


    }

我在 cmd 上收到一条消息“进程因 StackOverFlowException 而终止。”

我的代码有问题吗? 如果没有,你能帮我解决这个过流问题吗 注意:我只想要一个递归回溯算法;我不是在寻找任何超出我的联盟的花哨、有创意的东西。

感谢转发!

【问题讨论】:

    标签: c# algorithm combinations subset backtracking


    【解决方案1】:

    忽略我的第一条评论,你在调用combo后增加a,因此你被卡住了

    static void Combo(int a,int b, int c)
        {
            if (a != 10)
            {
                Combo(a, b, c);
                a++;  <-- This is never reached
    

    a 在其生命周期内保持为 0 尝试在调用组合期间递增,例如

        static void Combo(int a,int b, int c)
        {
            if (a >= 10)
            {
                Combo(++a, b, c);
    

    经过进一步测试,我相信您遵循以下(带有增量的嵌套 if 语句):

        static void Combo(int a, int b, int c)
        {
            Console.WriteLine("( {0}, {1}, {2})", a, b, c);
            if (a < 10)
            {
                Combo(++a, b, c);
                if (b < 10)
                {
                    Combo(a, ++b, c);
                    if (c < 10)
                    {
                        Combo(a, b, ++c);
                    }
                }
            }
        }
    

    【讨论】:

    • 仍然......这并没有给出整个组合......我们是否需要在关闭每个 if 语句时编写嵌套的 Else 语句?这完全解决了吗?
    • 尝试将结果添加到列表中?无法显示所有 1000 个结果可能是控制台的限制。
    【解决方案2】:

    正如其他人所建议的那样,您永远不会到达允许您增加计数器的行。 试试这个算法,它给你所有的“xxx”组合(000 到 999)并且还避免了重复的生成(Sayse 的解决方案会生成重复):

    static void Combo(int a, int b, int c)
    {
        if (a < 10)
        {
            if (b < 10)
            {
                if (c < 10)
                {
                    Console.WriteLine("( {0}, {1}, {2})", a, b, c);
                    Combo(a, b, ++c);
                }
                else
                {
                    c = 0;
                    Combo(a, ++b, c);
                }
            }
            else
            {
                c = 0; b = 0;
                Combo(++a, b, c);
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2013-03-29
      • 2012-03-22
      • 1970-01-01
      • 2015-07-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多