标签:生成 rgb length cheng lan == 题解 lse size
搬个官方题解
class Solution { bool valid(const string& str) {//验证是否合法 int balance = 0; for (char c : str) { if (c == ‘(‘) { ++balance; } else { --balance; } if (balance < 0) { return false; } } return balance == 0; } void generate_all(string& current, int n, vector<string>& result) { if (n == current.size()) { if (valid(current)) { result.push_back(current); } return; } current += ‘(‘; generate_all(current, n, result); current.pop_back(); current += ‘)‘; generate_all(current, n, result); current.pop_back(); } public: vector<string> generateParenthesis(int n) { vector<string> result; string current; generate_all(current, n * 2, result); return result; } };
class Solution { public List<String> generateParenthesis(int n) { List<String> ans = new ArrayList<String>(); backtrack(ans, new StringBuilder(), 0, 0, n); return ans; } public void backtrack(List<String> ans, StringBuilder cur, int open, int close, int max) { if (cur.length() == max * 2) { ans.add(cur.toString()); return; } if (open < max) { cur.append(‘(‘); backtrack(ans, cur, open + 1, close, max); cur.deleteCharAt(cur.length() - 1); } if (close < open) { cur.append(‘)‘); backtrack(ans, cur, open, close + 1, max); cur.deleteCharAt(cur.length() - 1); } } } 作者:LeetCode-Solution 链接:https://leetcode-cn.com/problems/generate-parentheses/solution/gua-hao-sheng-cheng-by-leetcode-solution/ 来源:力扣(LeetCode) 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
标签:生成 rgb length cheng lan == 题解 lse size
原文地址:https://www.cnblogs.com/libin123/p/14933785.html