leecode題解22- Generate Parentheses

題目:

Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.

For example, given n = 3, a solution set is:

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


思路: 回溯法

The idea here is to only add ‘(’ and ‘)’ that we know will guarantee us a solution (instead of adding 1 too many close). Once we add a ‘(’ we will then discard it and try a ‘)’ which can only close a valid ‘(’. Each of these steps are recursively called.

代碼1:反向

class Solution {
public:
    // 回溯法
    vector<string> generateParenthesis(int n) {
        vector<string> result;
        backTracking(result, "", n, n);   
        return result;
    }
    // slt 目標vector; str 當前字符串; left 待插入左括號個數; right 待插入右括號個數
    void backTracking(vector<string> &rlt, string str, int left, int right){
        // 若沒有待插入的左右括號時,滿足條件
        if(left==0 && right==0){
            rlt.push_back(str);
            return;
        }
        //如果還有待插入的左括號,插入左括號
        if(left > 0) backTracking(rlt, str+"(", left-1, right);
        // 如果 待插入的右括號個數 多於 待插入的左括號個數,則插入右括號
        if(right > left) backTracking(rlt, str+")", left, right-1);
    }
};

代碼2:正向

class Solution {
public:
    // 回溯法
    vector<string> generateParenthesis(int n) {
        vector<string> result;
        backTracking(result, "", 0, 0, n);   
        return result;
    }
    // slt 目標vector; str 當前字符串; left 當前字符串左括號個數; right 當前字符串右括號個數; max 最大單向括號個數
    void backTracking(vector<string> &rlt, string str, int left, int right, int max){
        // 若當前字符串長度等於 max*2, 滿足條件
        if(str.length() == max*2){
            rlt.push_back(str);
            return;
        }
        //如果左括號還沒有插入max個,則插入左括號
        if(left < max) backTracking(rlt, str+"(", left+1, right, max);
        // 如果當前右括號個數小於當前左括號個數,則可以插入右括號
        if(right < left) backTracking(rlt, str+")", left, right+1, max);
    }
};


發佈了49 篇原創文章 · 獲贊 3 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章