c# - 使用回溯算法生成组合

标签 c# algorithm combinations subset backtracking

我一直致力于使用回溯算法生成 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 而终止。”

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

感谢转发!

最佳答案

忽略我的第一条评论,你在调用 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);
                }
            }
        }
    }

关于c# - 使用回溯算法生成组合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23173222/

相关文章:

c - 确定一个字符串是否具有所有唯一字符?

algorithm - shell脚本中关联数组的时间复杂度

algorithm - 将 n 个相同的球分配到组中以使每组至少有 k 个球的方法有多少种?

arrays - Ruby n 个不同大小的数组中的 2 个的独特组合

c# - 有没有人知道 SQL Server 错误号 C# 包装器?

C# - 国际设置的 Excel 数字格式问题

c# - 可以得到 "operator"结果的引用吗?

c# - 如何在 asp.net mvc 中将动态创建的字段绑定(bind)到表单提交的数组?

java - 如何使用 FileReader 确保在 Java 中找到文件?

r - 查找属性变量的组合对