22. Generate Parentheses

Givennpairs of parentheses, write a function to generate all combinations of well-formed parentheses.

For example, givenn= 3, a solution set is:

[
  "((()))",
  "(()())",
  "(())()",
  "()(())",
  "()()()"
]

思路:回溯,注意第二个loop是close<open

 public List<String> generateParenthesis(int n) {
        List<String> list = new ArrayList<String>();
        backtrack(list, "", 0, 0, n);
        return list;
    }

    public void backtrack(List<String> list, String str, int open, int close, int max){

        if(str.length() == max*2){
            list.add(str);
            return;
        }

        if(open < max)
            backtrack(list, str+"(", open+1, close, max);
        if(close < open)
            backtrack(list, str+")", open, close+1, max);
    }

C++ code

class Solution {
public:
    vector<string> generateParenthesis(int n) {
        vector<string> list;
        string temp;
        backtrace(list, temp, 0, 0, n);
        return list;
    }

    void backtrace(vector<string>& list,string temp, int left, int right, int n){
        if (temp.size()== n*2){
            list.push_back(temp);
            return;
        }

        if (left<n){
            temp.push_back('(');
            backtrace(list, temp, left+1, right, n);
            temp.pop_back();
        }
        if (right<left){
            temp.push_back(')');
            backtrace(list, temp, left, right+1, n);
            temp.pop_back();
        }
        return;
    }
};

results matching ""

    No results matching ""