Skip to content

Instantly share code, notes, and snippets.

@QApolo
Created August 21, 2020 06:30
Show Gist options
  • Save QApolo/ee593b237ee1467e3451c8c4d77ac087 to your computer and use it in GitHub Desktop.
Save QApolo/ee593b237ee1467e3451c8c4d77ac087 to your computer and use it in GitHub Desktop.
suggested problem Stanford, first problem
//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