牛客题目链接:不重复打印排序数组中相加和为给定值的所有三元组
Leetcode题目链接:三数之和
牛客题目输入为有序数组,力扣未排序,要求输出结果无重复。
法一:DFS(复杂度为n^3, 超时)
# 牛客解法
inp = input().split()
n, k = int(inp[0]), int(inp[1])
arr = []
inp = input().split()
for i in range(n):
arr.append(int(inp[i]))
res = []
def dfs(tmp, idx):
if len(tmp) == 3:
if sum(tmp) == k:
res.append(tmp)
return
for i in range(idx, len(arr)):
if i > 0 and arr[i] == arr[i-1]:
continue
dfs(tmp+[arr[i]], i+1)
dfs([], 0)
for k in res:
print(k[0], k[1], k[2])
# 力扣解法
class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
res = []
nums.sort()
def check(tmp, s, idx):
if s == 0 and len(tmp) == 3 and tmp not in res:

该博客探讨如何在排序数组中找到所有相加和为给定值的不重复三元组。分别介绍了两种方法:深度优先搜索(DFS)和双指针技术。DFS方法虽然超时,但提供了思路;双指针方法能有效避免重复并提高效率。
最低0.47元/天 解锁文章
268

被折叠的 条评论
为什么被折叠?



