I've been struggling with this pretty tricky problem for the past week :( I have to find all combinations of numbers that sum up to a given natural number using recursion. I'm not allowed to use LINQ or anything else besides "using system"
For example if the input is 7 then the output should look like this:
1 + 1 + 1 + 1 + 1 + 1 + 1
2 + 1 + 1 + 1 + 1 + 1
2 + 2 + 1 + 1 + 1
2 + 2 + 2 + 1
3 + 1 + 1 + 1 + 1
3 + 2 + 1 + 1
3 + 2 + 2
3 + 3 + 1
4 + 1 + 1 + 1
4 + 2 + 1
4 + 3
5 + 1 + 1
5 + 2
6 + 1
The numbers from the combination should be listed exactly in that order so for an input of 3 for example the output should be exactly as follows:
1 + 1 + 1
2 + 1
For an input of 4 the output should look like this:
1 + 1 + 1 + 1
2 + 1 + 1
2 + 2
3 + 1
For every new list of combinations we increment the first number in the list and then we continue with the remaining part of the previous list until the sum will be equal with the input.
Just positive numbers are allowed between 1 (1 included) and input - 1.
My code so far gives me the following output for the same given input of 7:
+ 1
+ 1 + 1 + 2
+ 1 + 1 + 1
+ 2 + 2 + 3
+ 1 + 1 + 1
+ 1 + 1 + 2
+ 2 + 1
+ 1 + 1 + 2
+ 2 + 2 + 1
+ 3 + 3 + 4
+ 1 + 1 + 1
+ 1 + 1 + 2
+ 1 + 1 + 1
+ 2 + 2 + 3
+ 2 + 1
+ 1 + 1 + 2
+ 1 + 1 + 1
+ 2 + 2 + 3
...
Can you please help me with some suggestions?
static string GenerateCombinations(int n)
{
string combinationList = "";
for (int index = 1; index < n - 1; index++)
{
string intermediaryList = GenerateCombinations(n - index, index) + " + " + index;
combinationList += intermediaryList;
}
return combinationList + "\n";
}
static string GenerateCombinations(int n, int index)
{
string combinationList = "";
for (int i = 1; i < n - 1; i++)
{
if (i <= index)
{
string intermediaryList = GenerateCombinations(n) + " + " + index;
combinationList += intermediaryList;
}
}
return combinationList;
}
static void Main()
{
int n = Convert.ToInt32(Console.ReadLine());
Console.WriteLine(GenerateCombinations(n));
}