leetcode 22. Generate Parentheses-回溯|递归

原题链接:22. Generate Parentheses

【思路-Java、Python】 递归实现

采用递归方式,添加左括号的条件是左括号数量小于 n,添加右括号的条件是右括号数小于左括号数:

public class Solution {
    public List<String> generateParenthesis(int n) {
        List<String> res = new ArrayList<String>();
        dfs(res, "", n, 0, 0);
        return res;
    }
    public void dfs(List<String> res, String temp, int n, int left, int right) {
        if(right == n) {
            res.add(temp);
            return;
        }
        if (left < n) dfs(res, temp+"(", n, left+1, right);
        if (right < left) dfs(res, temp+")", n, left, right+1);
    }
}
8 / 8  test cases passed. Runtime: 2 ms  Your runtime beats 26.33% of javasubmissions.

class Solution(object):
    def generateParenthesis(self, n):
        """
        :type n: int
        :rtype: List[str]
        """
        res = []
        def dfs(res, n, s, left, right) :
            if right == n : res.append(s)
            if left < n :
                dfs(res, n, s + "(", left+1, right)
            if left > right :
                dfs(res, n, s + ")", left, right+1)
        dfs(res, n, '', 0, 0)
        return res
8 / 8  test cases passed. 8 / 8 test cases passed.  Your runtime beats 66.46% of pythonsubmissions.

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值