class Solution(object): def fourSum(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[List[int]] """ l = len(nums) nums.sort() if l < 4: return [] res = [] for i in range(l-3): if i > 0 and nums[i] == nums[i-1]: continue elif nums[i] + nums[i+1] + nums[i+2] + nums[i+3] > target: break elif nums[i] + nums[l-3] + nums[l-2] + nums[l-1] < target: continue for j in range(i+1, l-2): if j > i+1 and nums[j] == nums[j-1]: continue elif nums[i] + nums[j] + nums[j+1] + nums[j+2] > target: break elif nums[i] + nums[j] + nums[l-2] + nums[l-1] < target: continue k = j+1 p = l-1 s = target - nums[i] - nums[j] while k < p: if nums[k] + nums[p] > s: p -= 1 elif nums[k] + nums[p] < s: k += 1 else: res.append([nums[i], nums[j], nums[k], nums[p]]) while k < p and nums[k] == nums[k+1]: k += 1 while k < p and nums[p] == nums[p-1]: p -= 1 k += 1 p -= 1 return res
本文深入探讨了四数之和问题的解决方案,通过详细解释一个Python类的实现过程,展示了如何在给定一个整数数组和目标值的情况下,找出所有可能的四个数的组合,使得它们的和等于目标值。文章提供了完整的代码示例,并对关键步骤进行了注释说明。
407

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



