mirror of
https://github.com/Manoj-HV30/dsa-competitive-programming.git
synced 2026-05-16 19:35:22 +00:00
leetcode new problems
This commit is contained in:
@@ -0,0 +1,25 @@
|
||||
class Solution {
|
||||
public:
|
||||
vector<string> generateParenthesis(int n) {
|
||||
vector<string> res;
|
||||
dfs(0,0, "", n,res);
|
||||
return res;
|
||||
}
|
||||
void dfs(int openP, int closeP, string s, int n, vector<string> & res){
|
||||
if(openP == closeP && openP+closeP == 2*n){
|
||||
res.push_back(s);
|
||||
return;
|
||||
}
|
||||
|
||||
if(openP<n){
|
||||
dfs(openP+1, closeP, s+'(', n ,res);
|
||||
}
|
||||
if(closeP<openP){
|
||||
dfs(openP, closeP+1, s+')',n,res);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
//The recursion goes as deep as possible by completing one full parentheses string before coming back and trying another option.
|
||||
//Each recursive call explores one path fully, then backtracks — which is exactly depth-first search
|
||||
//Note we are passing s by value, so no need to reset it for every path
|
||||
@@ -0,0 +1,33 @@
|
||||
class Solution {
|
||||
public:
|
||||
vector<string> ans;
|
||||
void helper(string s,int open,int close) {
|
||||
if(open==0 && close==0) {
|
||||
ans.push_back(s);
|
||||
return;
|
||||
}
|
||||
if(open>0) {
|
||||
s+='(';
|
||||
helper(s,open-1,close);
|
||||
s.pop_back();
|
||||
}
|
||||
if(close>0) {
|
||||
if(open<close) {
|
||||
s+=')';
|
||||
helper(s,open,close-1);
|
||||
s.pop_back();
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
vector<string> generateParenthesis(int n) {
|
||||
helper("",n,n);
|
||||
return ans;
|
||||
}
|
||||
};
|
||||
|
||||
//This solution uses DFS with backtracking to generate all valid parentheses by exploring one complete construction path at a time.
|
||||
//pop_back() is used to backtrack by removing the last added character, as string s is passed by reference, hence more optimal
|
||||
|
||||
//TC : O(Cn), catalan number, The number of valid parentheses strings with n pairs is the n-th Catalan number.
|
||||
//SC: O(n)
|
||||
Reference in New Issue
Block a user