22. Generate Parentheses

不知道最佳答案()()()()()如何生成。

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

你可能感兴趣的:(22. Generate Parentheses)