You can use two stacks, negStack
and posStack
; negStack
is initialized with all of the negative parentheses in order with -1 at the top, posStack
is empty to start. Whenever you pop a negative parenthesis from negStack
you push its positive counterpart to posStack
.
On each recursive call you can either pop from negStack
(assuming it's non-empty) and push to postStack
, or you can pop from posStack
(assuming it's non-empty). This means that your recursive method would look like
void recurrence(Stack negStack, Stack posStack) {
// first recursive call: pop from negStack
int neg = negStack.pop();
posStack.push(-1 * neg);
recurrence(negStack, posStack);
// restore stacks
posStack.pop();
negStack.push(neg);
// second recursive call: pop from posStack
int pos = posStack.pop();
recurrence(negStack, posStack);
// restore stacks
posStack.push(pos);
}
I've omitted the checks to see if negStack
or posStack
is empty, as well as the code to store and print the results etc (e.g. you could use another stack to store the parentheses' running total, then print the stack contents when negStack
and posStack
are empty).