三元组,二元组,排列组合

"""
    算法题:二元组
    Given an array of integers, return indices of the two numbers such that they add up to a specific target.

    You may assume that each input would have exactly one solution, and you may not use the same element twice.
    Example:
    Given nums = [2, 7, 11, 15], target = 9,

    Because nums[0] + nums[1] = 2 + 7 = 9,
    return [0, 1].
    
    auther:Jacob
"""
 
class Solution: 
    def permute(self,numbers,target,num): 
        result = [] permute_result = list(itertools.permutations(numbers,num)) for i in                             
        permute_result: if sum(i) == target: result.append(i) 
        return result 
if __name__ == '__main__': 
    nums = [2, 7, 11, 15] 
    solution = Solution() 
    print(solution.permute(nums,9,2))

  * 算法题:三元组  *
 给出一个有 n 个整数的数组 S,在 S 中找到三个整数 a, b, c,使得 a + b + c = 0。写一个函数找到所有满足要求的三元组。  *  注意事项:  在三元组(a, b, c),要求a <= b <= c。结果不能包含重复的三元组。   格式:   输入行输入一个有 n 个整数的数组 S,最后输出所有满足要求的三元组。   样例输入   S = [ -1,0,1,2,-1,-4 ]   样例输出   ( -1, 0, 1 )  ( -1, -1, 2 )  """ 

class Solution:
    """
    @param numbersbers : Give an array numbersbers of n integer
    @return : Find all unique triplets in the array which gives the sum of zero.
    """

    def threeSum(self, numbers):
      
        result = []
        combinations = list(itertools.combinations(numbers, 3))
        for i in combinations:
            if sum(i) == 0 and sorted(list(i)) not in result:
                i = list(i)
                i.sort()
                result.append(i)
        return sorted(result)

if __name__ == '__main__':
    nums = [-1,0,1,2,-1,-4]
  
    solution = Solution()
    print(solution.threeSum(nums))

 给一个包含 n 个整数的数组 num,写一个函数找到和与给定整数 target 最接近的三元组,返回这三个数的和。 注意事项: 只需要返回三元组之和,无需返回三元组本身。 格式: 输入行依次输入一个整数数组 num 和一个给定的整数 target,最后输出和与 target 最接近的三元组的和。 样例输入 num = [ -1,2,1,-4 ] target = 1 样例输出 2   // -1 + 2 + 1 = 2 

import itertools


class Solution:
  

    def threeSumClosest(self, numbers, target):
        # write your code here


        combinations = list(itertools.combinations(numbers, 3))
        minNumber = sum(combinations[0])
        for i in combinations:
            if abs(sum(i) - target) < abs(minNumber - target):
                minNumber = sum(i)

        return minNumber


if __name__ == '__main__':
    nums =[-1, 2, 1, -4]

    solution = Solution()
    print(solution.threeSumClosest(nums,1))

 

 

 

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值