欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

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

程序员文章站 2024-01-16 10:48:10
...
"""
    算法题:二元组
    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))