22. Generate Parentheses - Medium

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:

[
  "((()))",
  "(()())",
  "(())()",
  "()(())",
  "()()()"
]

 

M1: backtracking

只用一个stringbuilder,每一层递归完,删掉最后一个char,回到上一层

time: O(2^n), space: O(n)

class Solution {
    public List<String> generateParenthesis(int n) {
        List<String> res = new ArrayList<>();
        backtracking(n, n, new StringBuilder(), res);
        return res;
    }
    
    private void backtracking(int l, int r, StringBuilder sb, List<String> res) {
        if(l > r || l < 0 || r < 0) return;
        if(l == 0 && r == 0)
            res.add(sb.toString());
        if(l > 0) {
            backtracking(l - 1, r, sb.append("("), res);
            sb.deleteCharAt(sb.length() - 1);
        }
        if(r > 0) {
            backtracking(l, r - 1, sb.append(")"), res);
            sb.deleteCharAt(sb.length() - 1);
        }
    }
}

 

M2: dfs

符合条件的能被加入res中的字符串,有n个 ( 和n个),当sb的长度为2n时,加入res。在recursion的时候,判断string是否符合条件,可以用两个参数l, r表示 ( 和 ) 剩余的个数,如果递归过程中,字符串中)的个数大于(的个数,即l > r,字符串不符合条件;否则,当 l 和 r 都 = 0时,把字符串加入res。

time: O(2^n), space: O(n)

class Solution {
    public List<String> generateParenthesis(int n) {
        List<String> res = new ArrayList<>();
        backtracking(n, n, "", res);
        return res;
    }
    
    private void backtracking(int l, int r, String s, List<String> res) {
        if(l > r || l < 0 || r < 0) return;
        if(l == 0 && r == 0)
            res.add(s);
        if(l > 0)
            backtracking(l - 1, r, s + "(", res);
        if(r > 0)
            backtracking(l, r - 1, s + ")", res);
    }
}

 

另一种写法

time: O(2 ^ 2n), space: O(2 ^ 2n)

class Solution {
    public List<String> generateParenthesis(int n) {
        List<String> res = new ArrayList<>();
        dfs(n, 0, 0, new StringBuilder(), res);
        return res;
    }
    
    private void dfs(int n, int l, int r, StringBuilder sb, List<String> res) {
        if(l == n && r == n) {
            res.add(sb.toString());
            return;
        }
        
        if(l < n) {
            sb.append("(");
            dfs(n, l + 1, r, sb, res);
            sb.deleteCharAt(sb.length() - 1);
        }
        if(l > r) {
            sb.append(")");
            dfs(n, l, r + 1, sb, res);
            sb.deleteCharAt(sb.length() - 1);
        }
    }
}

 

posted @ 2018-12-07 12:12  fatttcat  阅读(136)  评论(0编辑  收藏  举报