Assume we need to list four numbers A, B, C, and D. The sum of A+B+C+D is 10 and the value of each number is in the range of [0, 10].
Find all the possible combination.
The brute-force way is as follows:
for (int A = 0; A <=10; ++A)
for (int B = 0; B <=10-A; ++B)
{
if (A + B > 10) break;
for (int C = 0; C <=10-A-B; ++C)
{
if (A + B + C > 10) break;
for (int D = 0; D <=10-A-B-C; ++D)
{
if (A + B + C + D == 10)
{
cout << "A: " << A << ",B: " << B << ",C: " << C << ",D: " << D << endl;
break;
}
else if (A + B + C + D > 10)
break;
}
}
}
Q> Is there a better solution?
FYI: code is updated based on suggestion from @rici