Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth
Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

42,753 questions

55,518 answers

573 users

How to generates all valid permutations of parentheses for a given n in C++

1 Answer

0 votes
#include <iostream>
#include <vector>
#include <string>

/*
    Generate all valid parentheses combinations for a given n.
    The algorithm uses backtracking:

    - At any point, we may add '(' if we still have some left to place.
    - We may add ')' only if it won't break correctness:
      meaning we already placed more '(' than ')'.

    This ensures we never build invalid partial strings,
    which keeps the search efficient and avoids unnecessary work.
*/

// A helper function that performs the recursive construction.
void buildParentheses(
    int openRemaining,      // how many '(' we can still add
    int closeRemaining,     // how many ')' we can still add
    std::string& current,   // the current partial string
    std::vector<std::string>& result // where we store completed valid strings
) {
    // When both counters reach zero, we have a complete valid combination.
    if (openRemaining == 0 && closeRemaining == 0) {
        result.push_back(current);
        return;
    }

    // If we can still place an opening parenthesis, do so.
    if (openRemaining > 0) {
        current.push_back('(');
        buildParentheses(openRemaining - 1, closeRemaining, current, result);
        current.pop_back(); // backtrack
    }

    // We can place a closing parenthesis only if it keeps the string valid.
    // That means we must have placed more '(' than ')' so far.
    if (closeRemaining > openRemaining) {
        current.push_back(')');
        buildParentheses(openRemaining, closeRemaining - 1, current, result);
        current.pop_back(); // backtrack
    }
}

// A convenience wrapper that returns all valid parentheses combinations.
std::vector<std::string> generateParentheses(int n) {
    std::vector<std::string> result;
    std::string current;

    // We start with n '(' and n ')' available.
    buildParentheses(n, n, current, result);
    
    return result;
}

int main() {
    int n = 3; // You can change this to any positive integer.

    auto combos = generateParentheses(n);

    std::cout << "Valid parentheses combinations for n = " << n << ":\n";
    for (const auto& s : combos) {
        std::cout << "  " << s << "\n";
    }
}


/*
run:

Valid parentheses combinations for n = 3:
  ((()))
  (()())
  (())()
  ()(())
  ()()()

*/

 



answered 3 days ago by avibootz
...