Your decision looks right.
Right now, you basically give up all the options and print every solution. If you want only one solution, you can add the flag that you set when one solution was found, and check before proceeding with recursive calls.
For memoization, you must first get rid of the binary array, after which you can do something like this:
int memo[NUM_ELEMENTS][MAX_SUM][MAX_K]; bool subset_sum(int target, int i, int sum, int *a, int size, int K) { if (sum == target && !K) { memo[i][sum][K] = true; return memo[i][sum][K]; } else if (sum < target && i < size) { if (memo[i][sum][K] != -1) return memo[i][sum][K]; memo[i][sum][K] = foo(target, i + 1, sum + a[i], a, size, K-1) || foo(target, i + 1, sum, a, size, K); return memo[i][sum][K] } return false; }
Then look at memo[_all indexes_][target][K] . If so, then there is at least one solution. You can save additional information to get this next solution, or you can iterate with i from found_index - 1 to 0 and check for which i you have memo[i][sum - a[i]][K - 1] == true . Then take it and so on. This will allow you to restore the solution using only the memo array.
source share