Created
August 21, 2020 06:30
-
-
Save QApolo/ee593b237ee1467e3451c8c4d77ac087 to your computer and use it in GitHub Desktop.
suggested problem Stanford, first problem
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//https://web.stanford.edu/class/cs9/lectures/RecursionProbSetA.pdf | |
#include <iostream> | |
#include <vector> | |
using namespace std; | |
class Solution { | |
public: | |
enum TypeParenthesis {Open = 1, Close = -1}; | |
void generateParentheses(int size) { | |
if(size % 2 != 0) { | |
return; | |
} | |
vector <char> result; | |
this -> generateParentheses(TypeParenthesis::Open, result, size); | |
this -> generateParentheses(TypeParenthesis::Close, result, size); | |
} | |
private: | |
void generateParentheses(TypeParenthesis type, vector <char> &result, int size, int balance = 0) { | |
if(balance == 0 and result.size() == size) { | |
if(type == TypeParenthesis::Close) { | |
/**=== Instead of printing it could be added to a vector result === **/ | |
for(auto c: result) { | |
std::cout << c; | |
} | |
/**===**/cout << endl;/**===**/ | |
} | |
return; | |
} | |
else if(result.size() == size) { | |
return; | |
} | |
if(balance < 0) | |
return; | |
if(type == TypeParenthesis::Open) | |
result.push_back('('); | |
else | |
result.push_back(')'); | |
generateParentheses(TypeParenthesis::Open, result, size, balance + type); | |
generateParentheses(TypeParenthesis::Close, result, size, balance + type); | |
result.pop_back(); | |
} | |
}; | |
int main() { | |
Solution sol; | |
sol.generateParentheses(12); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment