刷题成瘾,不疯魔不成活。

最近主打回溯法相关的算法,第一个攻克的就是配对括号生成问题。

Question

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:

[
“((()))”,
“(()())”,
“(())()”,
“()(())”,
“()()()”
]

简单来说,给一个非有序的数字数组,然后给定一个target,计算有多少组不重复的集合,加起来的和为给定的target

Analysis

面对NSum问题,最简单最快捷的方法就是暴力枚举,但时间复杂度是O(N^3)。

基本思路就是先排序,然后外面套两层循环,target减去得出来的和,然后开始2Sum的方法,左右两边向中间移动。

每次左边和右边加起来的和等于target,这就是命中的一组。其中需要进行去重处理,其他的都是中规中矩的做法。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
class Solution(object):
'''
题意:找到数列中所有和等于目标数的四元组,需去重
多枚举一个数后,参照3Sum的做法,O(N^3)
'''
def fourSum(self, nums, target):
nums.sort()
res = []
length = len(nums)
for i in range(0, length - 3):
if i and nums[i] == nums[i - 1]:
continue
for j in range(i + 1, length - 2):
if j != i + 1 and nums[j] == nums[j - 1]:
continue
sum = target - nums[i] - nums[j]
left, right = j + 1, length - 1
while left < right:
if nums[left] + nums[right] == sum:
res.append([nums[i], nums[j], nums[left], nums[right]])
right -= 1
left += 1
while left < right and nums[left] == nums[left - 1]:
left += 1
while left < right and nums[right] == nums[right + 1]:
right -= 1
elif nums[left] + nums[right] > sum:
right -= 1
else:
left += 1
return res

Reference

4Sum - LeetCode