美文网首页
算法---求四数之和

算法---求四数之和

作者: reedthinking | 来源:发表于2017-07-15 21:52 被阅读0次

给定一个数组,求四个元素为target的所有组合

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
__title__ = ''
__author__ = 'thinkreed'
__mtime__ = '2017/3/19'

idea from https://discuss.leetcode.com/topic/22705/python-140ms-beats-100-and-works-for-n-sum-n-2/4
"""


class Solution(object):
    def fourSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[List[int]]
        """

        def find_N_sum(nums, start, target, n, result, results):
            #跳过剩余数组长度小于n或者当前的维次2或者target小于第一个数而太小不可能存在或者太大不存在的情况
            if len(nums[start:]) < n or n < 2 or target < nums[start] * n or target > nums[-1] * n:
                return
            #求两数和为target
            elif n == 2:
                left, right = start, len(nums) - 1

                while left < right:
                    cur_sum = nums[left] + nums[right]

                    if cur_sum < target:
                        left += 1
                    elif cur_sum > target:
                        right -= 1
                    else:
                        results.append(result + [nums[left], nums[right]])
                        left += 1
                        #跳过重复
                        while left < right and nums[left] == nums[left - 1]:
                            left += 1

            #降维次,将求n数和变为求n-1数和
            else:
                for i in range(len(nums[start:]) - n + 1):
                    if i == 0 or (i > 0 and nums[start + i - 1] != nums[start + i]):
                        find_N_sum(nums, start + i + 1, target - nums[start + i], n - 1, result + [nums[start + i]],
                                   results)

        results = []
        find_N_sum(sorted(nums), 0, target, 4, [], results)
        return results


if __name__ == '__main__':
    print(Solution().fourSum([1, 0, -1, 0, -2, 2], 0))

相关文章

  • 算法---求四数之和

    给定一个数组,求四个元素为target的所有组合

  • LeetCode 第18题:四数之和

    1、前言 2、思路 采用三数之和的思路,原本三数之和可以分解为:数组中的一个数 + 此数右边的数求两数之和,那么四...

  • 算法时间复杂度学习

    算法时间复杂度学习 1. 算法 算法:是用于解决特定问题的一系列的执行步骤。 举例: 简单的求两数之和,以及求n个...

  • leetcode top100

    1.求两数之和(数组无序) 2.求电话号码的字母组合 3.三数之和 4.两数之和(链表)

  • [算法基础题]求两数之和

    本文由黑壳博客原创 本文来源[算法基础题]求两数之和 今日总结 浪费生命的三座大山,迟到,防火墙,机械硬盘。 正文...

  • algrithrom

    求和问题,双指针解决 done 两数之和 三数之和 最接近三数之和 四数之和 链表反转问题 done 链表反转 链...

  • 最简单的算法题,你会吗?

    leetcode上算法第一题,求两数之和,是最简单的算法题。 给定一个整数数组 nums 和一个目标值 targe...

  • 算法:不使用加号,求两数之和

    算法 求两个数之和,但不能使用加号运算符 方法一: 方法二: 方法三: 方法四:

  • 数组求和

    问题1 数组里求两数之和等于目标数 原理 这个问题可能是很多人接触LeetCode的第一道算法题了 解法很多种我还...

  • 两数之和&三数之和&四数之和&K数之和

    今天看了一道谷歌K数之和的算法题,忽然想起来之前在力扣上做过2、3、4数之和的题,觉得很有必要来整理一下。其实2、...

网友评论

      本文标题:算法---求四数之和

      本文链接:https://www.haomeiwen.com/subject/cxvzhxtx.html