Monday, October 27, 2008

Careercup - Microsoft

Microsoft » Algorithm Coding » Software Engineer / Developer

Develop an algorithm to find out all valid combinations of n brackets. Like for n =3 possible combinations can be ((())) or ()()() or (()()) and so on.
Read Question »
- vodangkhoa on January 08, 2007 (29) |Edit |Edit | Question #2103 (Report Dup)

void GetCombination(int total, string existResult, int leftUsed, int rightUsed)
{
if (leftUsed == total && rightUsed == total)
{
Console.WriteLine(existResult);
}

if (total - leftUsed > 0)
{
GetCombination(total, existResult + "(", leftUsed + 1, rightUsed);
}

if (total - rightUsed > 0 && leftUsed > rightUsed)
{
GetCombination(total, existResult + ")", leftUsed, rightUsed + 1);
}
}

No comments: