[Lintcode]Generate Parentheses 生成括号
2016-09-25 17:34
495 查看
Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
Have you met this question in a real interview?
Yes
Example
Given
set is:
搜索每一种可能的结果,可以使用BFS或者DFS。BFS可是考虑使用队列。但这道题更适合用DFS求解。注意helper函数接收left和right变量,作为左括号和右括号剩余数量。注意当left小于right时,属于异常情况,括号不能完整匹配,所以此时直接返回即可。另外通过变量res储存结果。
public class Solution {
/**
* @param n n pairs
* @return All combinations of well-formed parentheses
*/
public ArrayList<String> generateParenthesis(int n) {
// DFS
ArrayList<String> res = new ArrayList<String>();
helper(n, n, n, "", res);
return res;
}
void helper(int n, int left, int right, String str, ArrayList<String> res) {
if(left > right) return;
if (left == 0 && right == 0) {
res.add(str);
return;
} else if (left == 0 && right != 0) {
while(right-- > 0) str += ")";
res.add(str);
return;
} else if (left != 0 && right == 0) {
return;
} else{
helper(n, left - 1, right, str + "(", res);
helper(n, left, right - 1, str + ")", res);
return;
}
}
}
Have you met this question in a real interview?
Yes
Example
Given
n = 3, a solution
set is:
"((()))", "(()())", "(())()", "()(())", "()()()"
搜索每一种可能的结果,可以使用BFS或者DFS。BFS可是考虑使用队列。但这道题更适合用DFS求解。注意helper函数接收left和right变量,作为左括号和右括号剩余数量。注意当left小于right时,属于异常情况,括号不能完整匹配,所以此时直接返回即可。另外通过变量res储存结果。
public class Solution {
/**
* @param n n pairs
* @return All combinations of well-formed parentheses
*/
public ArrayList<String> generateParenthesis(int n) {
// DFS
ArrayList<String> res = new ArrayList<String>();
helper(n, n, n, "", res);
return res;
}
void helper(int n, int left, int right, String str, ArrayList<String> res) {
if(left > right) return;
if (left == 0 && right == 0) {
res.add(str);
return;
} else if (left == 0 && right != 0) {
while(right-- > 0) str += ")";
res.add(str);
return;
} else if (left != 0 && right == 0) {
return;
} else{
helper(n, left - 1, right, str + "(", res);
helper(n, left, right - 1, str + ")", res);
return;
}
}
}
相关文章推荐
- LintCode算法题解
- LintCode Majority Number iii
- LintCode-最大数
- lintCode Intersection of Two Arrays II
- Intersection of Two Arrays
- Subtree
- LintCode
- LintCode --number-of-airplanes-in-the-sky(数飞机)
- LintCode --invert-binary-tree(翻转二叉树)
- LintCode --find-the-missing-number(寻找缺失的数)
- LintCode--best-time-to-buy-and-sell-stock(买卖股票的最佳时机)
- LintCode--best-time-to-buy-and-sell-stock-ii(买卖股票的最佳时机 II)
- lintcode之不同子序列数 + 序列II
- lintcode之快速幂
- lintcode删除排序数组中的重复数字 II
- lintcode之数组划分
- leetcode之三数之和 II
- lintcode之 数组剔除元素后的乘积
- lintcode之 合并排序数组 II
- lintcode 之子数组之和