输入:nums = [2, 2, 7, 6, 1, 7, 3, 6, 2, 3], target = 9 输出:[(2, 7), (3, 6), (6, 3), (7, 2)] 解释:组合成员间是有序的,但组合之间不重复。
时间: 2023-10-06 15:11:23 浏览: 49
这个问题属于技术问题,可以回答。这个问题可以使用双指针法来解决。我们先将数组排序,然后设置两个指针left和right,分别指向数组的首尾两个元素。然后,我们从左往右遍历数组,使用双指针法找到数组中所有两个数的和等于target的组合。具体实现可以参考以下代码:
def two_sum(nums, target):
nums.sort()
left, right = 0, len(nums) - 1
res = []
while left < right:
if nums[left] + nums[right] == target:
res.append((nums[left], nums[right]))
left += 1
right -= 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] < target:
left += 1
else:
right -= 1
return res
nums = [2, 2, 7, 6, 1, 7, 3, 6, 2, 3]
target = 9
print(two_sum(nums, target)) # 输出 [(2, 7), (3, 6), (6, 3), (7, 2)]