#include #include #include using namespace std; void allSolutions(int array[], int C, int n, int N) { if (n == 1) { array[n - 1] = C; for (int i = 0; i < N; i++) { cout << setw(3) << array[N - (i + 1)]; } cout << endl; } else { for (int i = 0; i < (C - (n - 1)); i++) { array[n - 1] = (i + 1); allSolutions(array, (C - (i + 1)), (n - 1), N); } } } int main(int argc, char* argv[]) { if (argc <= 1) { cout << "Usage: allsolutions [1 <= n <= C <= 10]" << endl; exit(0); } int n = atoi(argv[1]); int C = atoi(argv[2]); int x[n - 1]; if (n >= 1 && n <= C && C <= 10) { cout << "All solutions with n=" << n << " and C=" << C << ":" << endl; allSolutions(x, C, n, n); } else { cout << "Invalid input: n=" << n << " C=" << C << endl; cout << "Usage: allsolutions [1 <= n <= C <= 10]" << endl; } return 0; } // Here's an even shorter solution (four fewer lines of code). // In main, replace // allsolutions(x, C, n, n); // with these two lines: // string str = ""; // allSolutions(n, C, str); void allSolutions(int n, int C, string s) { if (n == 1) { cout << s << setw(3) << C << endl; } else { for (int i = 1; i <= (C - n + 1); i++) { allSolutions(n - 1, C - i, s + " " + char(i + '0')); } } }