标签:style blog color os io ar for div sp
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
标签:style blog color os io ar for div sp
原文地址:http://www.cnblogs.com/yuhaos/p/3958930.html