1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
|
public boolean (String s) { Stack<Character> stack = new Stack<Character>(); for (char c : s.toCharArray()) { if (c == '(') { stack.push(')'); } else if (c == '{') { stack.push('}'); } else if (c == '[') { stack.push(']'); } else if (stack.isEmpty() || stack.pop() != c) { return false; } } return stack.isEmpty(); }
public List<String> generateParenthesis(int n) { List<String> res = new ArrayList<>(); if (n <= 0) { return res; } genParenthesis(res, new StringBuilder(), 0, n * 2); return res; }
private void genParenthesis(List<String> res, StringBuilder sb, int index, int n) { if (sb.length() == n) { if (isValid(sb.toString())) { res.add(sb.toString()); } return; } sb.append('('); genParenthesis(res, sb, index + 1, n); sb.deleteCharAt(sb.length() - 1); sb.append(')'); genParenthesis(res, sb, index + 1, n); sb.deleteCharAt(sb.length() - 1); }
public void dfs(List<String> res, String cur, int l, int r) { System.out.println("res:" + cur); if(l == 0 && r == 0) { res.add(cur); return; } if(l > 0) { dfs(res, cur + "(", l - 1, r); } if(l < r) { dfs(res, cur + ")", l, r -1); }
}
public List<String> generateParenthesis2(int n) { List<String> res = new ArrayList<>(); if(n <= 0) { return res; } dfs(res, "", n , n); return res; }
|
近期评论