首页 > 代码库 > [LeetCode] Generate Parentheses
[LeetCode] Generate Parentheses
public class Solution { public List<String> generateParenthesis(int n) { List<String> result = new ArrayList<String>(); Stack<Integer> numStack = new Stack<Integer>(); int nowNum = n; boolean nowNumPoped = false; while (!(nowNumPoped && nowNum == n)) { if (!nowNumPoped) { if (nowNum>0) { numStack.push(nowNum); if (numStack.size()+nowNum == n+1) nowNum--; } else { result.add(generateString(numStack,n)); nowNum = numStack.pop(); nowNumPoped = true; } } else { nowNum--; nowNumPoped = false; } } return result; } public String generateString(Stack<Integer> numStack, int n) { int rightParentheses = 0; StringBuffer resultString = new StringBuffer(); for (int i=0; i<n; i++) { resultString.append("("); int tmpIndex = n-i-1; if (tmpIndex<numStack.size()) { while (rightParentheses<numStack.get(tmpIndex)) { resultString.append(")"); rightParentheses++; } } } return resultString.toString(); }}
[LeetCode] Generate Parentheses
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。