java 22.生成Parentheses.java

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java 22.生成Parentheses.java相关的知识,希望对你有一定的参考价值。

"""
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:

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

"""


class Solution(object):
    
    def helper(self,left,right,temp,res):
        if left > right:
            return;
        if left == 0 and right == 0:
            res.append(temp);
        if left > 0:
            self.helper(left - 1, right, temp + '(', res);
        if right > 0:
            self.helper(left, right - 1, temp + ')', res);
            
    def generateParenthesis(self, n):
        """
        :type n: int
        :rtype: List[str]
        """
        if not n:
            return [];
        
        res = [];
        self.helper(n,n,"",res);
        return res;
public class Solution {
    public List<String> generateParenthesis(int n) {
        
        List<String> res = new ArrayList<String>();
        StringBuilder temp = new StringBuilder();
        backtracking(n, n, temp, res);
        return res;
    }
    
    private void backtracking(int left, int right, StringBuilder temp, List<String> res) {
        if(left == 0 && right == 0) {
            res.add(temp.toString());
            return;
        }
        
        if(left > 0) {
            temp.append('(');
            backtracking(left - 1, right, temp, res);
            temp.setLength(temp.length() - 1);
        }
        
        if(right > left) {
            temp.append(')');
            backtracking(left, right - 1, temp, res);
            temp.setLength(temp.length() - 1);
        }
    }
}

以上是关于java 22.生成Parentheses.java的主要内容,如果未能解决你的问题,请参考以下文章

java 22.生成Parentheses.java

java 22.生成Parentheses.java

java 22.生成Parentheses.java

java 22.生成Parentheses.java

java 22.生成Parentheses.java

java刷题--22括号生成