22. Generate Parentheses
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了22. Generate Parentheses相关的知识,希望对你有一定的参考价值。
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:
"((()))", "(()())", "(())()", "()(())", "()()()"
AC代码:
class Solution(object): def generateParenthesis(self, n): if n < 1: return [‘‘] def backtracing(left, right, current, ret_list): if left > 0: backtracing(left - 1, right, current + ‘(‘, ret_list) if right > 0: if left == right: return backtracing(left, right - 1, current + ‘)‘, ret_list) else: ret_list.append(current) ret_list = [] backtracing(n, n, ‘‘, ret_list) return ret_list
用递归,找准递归出口即可。注意left==right的条件。
以上是关于22. Generate Parentheses的主要内容,如果未能解决你的问题,请参考以下文章
LeetCode 22. Generate Parentheses
Leetcode 22. Generate Parentheses