LeetCode--22--medium--GenerateParentheses

199 篇文章 0 订阅

summary:

dfs | backtrack

package myapp.kit.leetcode.top100liked;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

/**
*
* 22
* medium
* https://leetcode.com/problems/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:
*
* [
*   "((()))",
*   "(()())",
*   "(())()",
*   "()(())",
*   "()()()"
* ]
*
* @author Dingsheng Huang
* @date 2020/4/21 23:54
*/
public class GenerateParentheses {

// ====origin idea  O(N2)
List<String> result = new ArrayList<>();
public List<String> generateParenthesis(int n) {
dfs(n, new StringBuilder(), 1, 0, '(');
return result;
}
private void dfs(int n, StringBuilder path, int l, int r, Character ch) {
path.append(ch);
if (l > n || r > n || r > l) {
return;
}
if (path.length() == n * 2) {
if (validate(path)) {
}

}
dfs(n, path, l + 1, r, '(');
path.deleteCharAt(path.length() - 1);
dfs(n, path, l, r + 1,')');
path.deleteCharAt(path.length() - 1);

}

private boolean validate(StringBuilder stringBuilder) {
Stack<Character> stack = new Stack<>();

for (int i = 0; i < stringBuilder.length(); i++) {
if (stack.isEmpty()) {
stack.push(stringBuilder.charAt(i));
continue;
}
if (stack.peek() == '(' && stringBuilder.charAt(i) == ')') {
stack.pop();
} else {
stack.push(stringBuilder.charAt(i));
}
}
return stack.isEmpty();
}

// ====  optimize O(N)
public List<String> generateParenthesis2(int n) {
track(new StringBuilder(), 0, 0, n);
return result;
}

private void track(StringBuilder path, int l , int r, int n) {
if (path.length() == n * 2) {
return;
}
if (l < n) {
track(path.append("("), l + 1, r, n);
path.deleteCharAt(path.length() - 1);
}
if (r < l) {
track(path.append(")"), l, r + 1, n);
path.deleteCharAt(path.length() - 1);
}
}

}


• 0
点赞
• 0
收藏
觉得还不错? 一键收藏
• 打赏
• 0
评论

“相关推荐”对你有帮助么？

• 非常没帮助
• 没帮助
• 一般
• 有帮助
• 非常有帮助

¥2 ¥4 ¥6 ¥10 ¥20

1.余额是钱包充值的虚拟货币，按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载，可以购买VIP、C币套餐、付费专栏及课程。