2015年4月5日星期日

Generate Parentheses leetcode

Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.
For example, given n = 3, a solution set is:
"((()))", "(()())", "(())()", "()(())", "()()()"
1. 如果左括号数还没有用完,那么我们能继续放置左括号
2. 如果已经放置的左括号数大于已经放置的右括号数,那么我们可以放置右括号 (如果放置的右括号数大于放置的左括号数,会出现不合法组合)
所以,运用dfs在每一层递归中,如果满足条件先放置左括号,如果满足条件再放置右括号

返回条件: 左括号和右括号都用完的情况下返回
参数传入: 如果左侧增加一个括号 下次递归时候就是left- 1 右侧同理

public class Solution {
    public ArrayList<String> generateParenthesis(int n) {
        ArrayList<String> result = new ArrayList<String>();
        if (n <= 0){
            return result;
        }
        dfs(result, "", n, n);
        return result;
    }
    public void dfs(ArrayList<String> result, String tem, int left, int right){
        if (left == 0 && right == 0){
            result.add(tem);
            return;
        }
        if (left > 0){
            tem = tem + "(";
       
            dfs(result, tem, left-1 , right);
            tem = new String(tem.substring(0, tem.length() - 1));
        }
        if (left < right){
            tem = tem + ")";
         
            dfs(result, tem, left, right-1);
            tem = new String(tem.substring(0, tem.length() - 1));
        }
    }
}

更简便的方法: dfs时候直接带入新的tem 这样就不用改变tem的值了
public class Solution {
    public ArrayList<String> generateParenthesis(int n) {
        ArrayList<String> result = new ArrayList<String>();
        if (n <= 0){
            return result;
        }
        dfs(result, "", n, n);
        return result;
    }
    public void dfs(ArrayList<String> result, String tem, int left, int right){
        if (left == 0 && right == 0){
            result.add(tem);
            return;
        }
        if (left > 0){
            dfs(result, tem + "(", left - 1 , right);
        }
        if (left < right){
            dfs(result, tem = tem + ")", left, right - 1);
        }
    }
}

没有评论:

发表评论