leetcode-generate-parentheses 发表于 2016-12-01 | 分类于 算法 , leetcode | 题目大意 https://leetcode.com/problems/generate-parentheses/ 生成所有n个左括号和n个右括号的合法的组合 题目分析 经典的深度优先搜索或者说回溯法。 代码12345678910111213141516171819202122232425262728293031323334public class Solution { private Character[] path; private List<String> ans; public void search(int idx, int left, int right, int n) { if (idx >= 2 * n) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < 2 * n; i++) { sb.append(path[i]); } ans.add(sb.toString()); return; } if (left > 0) { path[idx] = '('; search(idx + 1, left - 1, right, n); if (left < right) { path[idx] = ')'; search(idx + 1, left, right - 1, n); } } else { path[idx] = ')'; search(idx + 1, left, right - 1, n); } } public List<String> generateParenthesis(int n) { path = new Character[2 * n]; ans = new ArrayList<String>(); search(0, n, n, n); return ans; }}