Leetcode 22 Generate Parentheses

HowieLee59發表於2018-10-18

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)

class Solution {
    public List<String> generateParenthesis(int n) {
        List<String> list = new ArrayList<>();
        backtrack(list,"",0,0,n);
        return list;
    }
    public void backtrack(List<String> list,String cur,int open,int close,int max){
        if(cur.length() == max * 2){
            list.add(cur);
            return;
        }
        if(open < max){
            backtrack(list,cur+"(",open + 1,close,max);
        }
        if(close < open){
            backtrack(list,cur+")",open,close + 1,max);
        }
        return ;
    }
}

2)

class Solution {
    public List<String> generateParenthesis(int n) {
        List<String> ret = new ArrayList<>();

        if (n == 0) {
            ret.add("");
        } else {
            for (int i = 0; i < n; i++) {
                for (String left: generateParenthesis(i)) {
                    for (String right: generateParenthesis(n - i - 1)) {
                        ret.add("(" + left + ")" + right);
                    }
                }
            }
        }

        return ret;
    }
}

第一個方法中使用了回溯

相關文章