【LeetCode】Generate Parenthesis - Medium

给定 n 对括号,请写一个函数以将其生成新的括号组合,并返回所有组合结果。

样例
给定 n = 3, 可生成的组合如下:
“((()))”, “(()())”, “(())()”, “()(())”, “()()()”

标签
递归 回溯法 字符串处理 谷歌 Zenefits

相关题目
容易有效的括号序列27 %中等
不同的二叉查找树 II33 %中等

(1)Java

public class GenerateParenthesis {
    public List<String> generateParenthesis(int n) {
        List<String> result = new ArrayList<String>();
        if (n <= 0) {
            return result;
        }
        helper(result, "", n, n);
        return result;
    }

    private void helper(List<String> result,
                        String parenPair, // current paren
                        int left, // how many left paren we need to add now
                        int right){
        if(left == 0 && right == 0){
            result.add(parenPair);
            return;
        }
        if(left > 0){
            helper(result, parenPair + "(", left - 1, right);
        }

        if(right > 0 && left < right){
            helper(result, parenPair + ")", left, right - 1);
        }
    }
}

(2)C++

class Solution {
public:
    vector<string> generateParenthesis(int n) {
        vector<string> result;
        generate("", n, n, result);
        return result;
    }
private:

/*
    item: 用来生成的括号字符串;
    n:括号的组数(每出现一对括号 "()" 为一组)

    递归需要限制条件:
     1.左、右括号最多放n个
     2. 若 '( ' <= ') ',不可进行放置右括号的递归!
*/
    void generate(string item_str, int left, int right,
        vector<string> &result) {
        if (left == 0 && right == 0 ) {// 当字符串item长度为括号对数的2倍时
            result.push_back(item_str);
            return;
        }
        if (left > 0) {
            generate(item_str + "(", left - 1, right, result);
        }
        if (left < right) {// 注意@ 左括号个数<右括号时,可递归生成右括号,而非'>'
            generate(item_str + ")", left, right - 1, result);
        }
    }
};

int main()
{
    Solution sol;
    vector<string> result = sol.generateParenthesis(3);
    for (int i = 0; i < result.size(); i++) {
        //cout << result[i].c_str() << endl;
        printf("%s\n", result[i].c_str());
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/ljyljyok/article/details/79461227