2014-04-19 36 views
1

我一直在努力使用所述回溯算法 號碼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而終止」。

有沒有我的代碼有問題? 如果沒有,請你幫我解決這個問題。流程問題 注意:我只需要一個遞歸回溯算法;我不尋找任何幻想,創造性超出我的聯盟。

Thanks Forwards!

回答

1

正如其他人所建議的,你永遠不會達到允許你增加計數器的界限。 試試這個算法,給你所有的「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); 
     } 
    } 
} 
2

忽略我的第一個評論,您遞增之後您調用組合,因此你作爲正是如此堅持

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語句w /增量):

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); 
       } 
      } 
     } 
    } 
+0

你有一個乾淨的心靈!如果......我從來沒有想過它! – Obzajd

+0

still ..這並不給出整個組合...... 我們是否需要在關閉每個if語句時編寫嵌套的Else語句? 這是否完全解決了它? – Obzajd

+0

嘗試將結果添加到列表中?這可能是控制檯無法顯示全部1000個結果的限制。 – Sayse