-
Notifications
You must be signed in to change notification settings - Fork 0
/
22. Generate Parentheses.txt
31 lines (31 loc) · 1.4 KB
/
22. Generate Parentheses.txt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
//Ìîé êîä
//Ïðîñòàÿ ðåêóðñèÿ. Îñíîâíàÿ ôóíêöèÿ âûçûâàåò ôóíêöèþ ðåêóðñèè. Â îñíîâíîé ôóíêöèè îïèñàíà ñòðîêà â êîòîðîé íàõîäÿòñÿ ñêîáêè "()".
// êàæäîé ôóíêöèè ðåêóðñèè ñíà÷àëà ïðîâåðÿåì óñëîâèÿ âûïîëíåíèÿ. Îòñåèâàåì íåâåðíûå âûâîäû. Åñëè âñå øàãè ïðîéäåíû òî çàïèñûâàåì îòâåò â âåêòîð.
//Äëÿ ðàçâåòâëåíèÿ â êàæäîé ôóíêöèè åñòü öèêë ïðîõîäÿùèé ïî îáîèì ñêîáêàì.
class Solution {
public:
void recursion(int n, int left,int right, int stepsNum, string variation,
vector<string>& answer, string parentheses) {
if (stepsNum == 0 && variation[variation.size() - 1] != '(')
answer.push_back(variation);
if (left <= n && left >= right && stepsNum > 0)
{
for(char parenthesis : parentheses)
{
if (parenthesis == '(')
recursion(n, left + 1, right, stepsNum - 1, variation + parenthesis, answer, parentheses);
else
recursion(n, left, right + 1, stepsNum - 1, variation + parenthesis, answer, parentheses);
}
}
}
vector<string> generateParenthesis(int n) {
string parentheses = { "()" };
int left = 1, right = 0;
int stepsNum = n * 2 - 1;
string variation = "(";
vector<string> answer;
recursion(n, left, right, stepsNum, variation, answer, parentheses);
return answer;
}
};