我一直致力于使用回溯算法生成 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/