-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path38.cpp
More file actions
69 lines (52 loc) · 1.68 KB
/
Copy path38.cpp
File metadata and controls
69 lines (52 loc) · 1.68 KB
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
#include <bits/stdc++.h>
using namespace std;
// Generate Parenthesis: Advanced Recursion and Backtracking
// https://leetcode.com/problems/generate-parentheses/description/
vector<string> valid;
// as we are going deep in recursion and getting back then we need to undo our changes thus pop back is used and this is only called backtracking
// string also pass by value and thus take O(n) time extra, thus make it mass by reference
void generate(string &s, int open, int close){
if(open == 0 && close == 0){
valid.push_back(s);
return;
}
if(open>0){
s.push_back('(');
generate(s, open -1, close);
s.pop_back();
}
if(close>0){
if(open < close){ // i.e. in string open brackets are more than close
s.push_back(')');
generate(s, open, close -1);
s.pop_back();
}
}
}
// time complexity in recursion -
// 1. function call kitni bar hua
// 2. and function ki time complexity kitni hai
// so yahan par
// ek function toh O(1) time complexity ka hai, kyunki koi bhi loop nahi chal raha and saare operation O(1) ke hain
// and ab har ek function mein worst case hai do bar genearte function chale
/*
O -> 2^0
O O -> 2^1
O O O O -> 2^2
-> 2^n
2^0 + 2^1 + 2^2 + 2^3 .... + 2^n this is gp
= 2*(2^n - 1) = 2^n+1 ~ 2^n
here in this question this n will be 2n of the question
thus time complexity O(2^2n) ~ O(2^n)
*/
int main() {
int n;
cin>>n;
string s;
generate(s, n, n);
for (auto &value : valid)
{
cout<<value<<endl;
}
return 0;
}