It is possible that a solution without a stack is possible, but the usual (and, as a rule, the easiest!) Way to implement reverse tracking algorithms is recursion, for example:
int i = 0, n; // i needs to be visible to show() int s[100]; // Considering only the subset of prob[] values whose indexes are >= start, // print all subsets that sum to total. void new_subsets(int start, int total) { if (total == 0) show(); // total == 0 means we already have a solution // Look for the next number that could fit while (start < n && prob[start] > total) { ++start; } if (start < n) { // We found a number, prob[start], that can be added without overflow. // Try including it by solving the subproblem that results. s[i++] = start; new_subsets(start + 1, total - prob[start]); i--; // Now try excluding it by solving the subproblem that results. new_subsets(start + 1, total); } }
Then you call this from main() with new_subsets(0, d); . Recursion may be difficult to understand at the beginning, but it is important that your head is around - try to simplify tasks (for example, generate Fibonacci numbers recursively) if the above does not make any sense.
Working instead of this solution, I see that as soon as you find a solution, you destroy it and start looking for a new solution from the number to the right of the first number that was included in this solution ( top = -1; i = s[top+1]; means i = s[0] , and there is a subsequent i++; ). This will skip decisions that start on the same first day. You should just do if (sum == d) { show(); } if (sum == d) { show(); } instead, to make sure you get them.
At first, I found your inner while rather confusing, but I think it really does the right thing: once i gets to the end of the array, it deletes the last number added to the partial solution, and if that number was the last number in the array, it will be loop again to remove the second-last number from the partial solution. It can never loop more than twice, because the numbers included in the partial solution are in different positions.
source share