C++ reverse stack problem

Problem Description:

Give you a stack, you can only use recursion, and can't open up additional data structures , and reverse this stack

Solution of ideas:

If we want to reverse the stack, we must first find a way to get the elements at the bottom of the stack, and we also need to re-press the elements above the bottom of the stack in the original order.

For example we have this stack

Open Baidu APP to see high-definition pictures

We need a function that takes out 1 without affecting the order of 2 and 3

We can do this:

First take out an element, and then determine whether it is empty

If it is empty, it returns directly to the current stack with just one element, the top of which is of course itself

Then we keep returning the answer up the bottom of the recursive function stack like this

So we recursively get the code at the bottom of the stack as follows

In our main function, we need to continuously take out the bottom of the stack, record the obtained value in each stack frame, and then return in turn

C++ substring problem 

Problem Description:

Given an arbitrary string, output all its subsequences

For example: "abc"

Output: "a", "b", "c", "ab", "ac", "bc", "abc"

Solution of ideas:

Our question, in fact, can be decomposed into two cases, a character to choose, or not to choose

We can traverse each string and judge whether they are selected or not selected, until all characters are judged, and then perform backtracking judgment

like this:

Open Baidu APP to see high-definition pictures


All we need the following parameters

Return the value array vector, when we use recursion, if we need to record the answer, it is best to use it as a reference parameter

Subscript index to determine whether the characters in the string have been judged

String path, record the current selection method

and our original array

The code is as follows, details can be seen in the comments

In the above code, we may encounter the problem of repeated substrings, for example, we need to find the substring of "accc"

has a lot of repetition

To avoid this problem, we'd better use the hashset (unordered_set) container when accepting the answer

Guess you like

Origin blog.csdn.net/weixin_55305220/article/details/123224452