递归搜索,尝试增加括号,如果剩余的括号里左括号多于右括号,则不可能完成任务,抛弃结果;
如果没有括号剩下,那么任务完成,把结果temp添加到ans。
注意python没有传参,需要不断对原list对象赋值。
https://www.cnblogs.com/ariel-dreamland/p/9133613.html
python还是太慢了啊……
提交时间 运行结果 运行时间 占用内存 使用语言
8秒前 答案正确 3ms 504KB C++
20秒前 答案正确 37ms 6520KB Python 3
#
# @param n int整型
# @return string字符串一维数组
#
class Solution:
def generateParenthesis(self, n):
# write code here
ans = []
return recurve(n, n, "", ans)
def recurve(left, right, temp, ans):
if left > right:
return ans
if left == 0 and right == 0:
ans.append(temp)
else:
if left > 0:
ans = recurve(left-1, right, temp + "(", ans)
if right > 0:
ans = recurve(left, right-1, temp + ")", ans)
return ans


京公网安备 11010502036488号