C#递归函数详细介绍及使用方法

2019-12-30 11:57:11于丽

true, true, true 
true, true, false 
true, false, true 
true, false, false 
false, true, true 
false, true, false 
false, false, true 
false, false, false如果n很大,且不用递归是很难解决这个问题的。 
复制代码
public void CompositionBooleans(string result, int counter) 

if (counter == 0) 
return; 
bool[] booleans = new bool[2] { true, false }; 
for (int j = 0; j < 2; j++) 

StringBuilder stringBuilder = new StringBuilder(result); 
stringBuilder.Append(string.Format("{0} ", booleans[j].ToString())).ToString(); 
if (counter == 1) 
Console.WriteLine(stringBuilder.ToString()); 
CompositionBooleans(stringBuilder.ToString(), counter - 1); 


现在让我们来调用上面这个方法: 
复制代码
CompositionBoolean(string.Empty, 3); 
Ian Shlasko建议我们这样使用递归: 
复制代码
public void BooleanCompositions(int count) 

BooleanCompositions(count - 1, "true"); 
BooleanCompositions(count - 1, "false"); 

private void BooleanCompositions(int counter, string partialOutput)