首页 > 解决方案 > 给定一个大小为 n 的数组 arr 和一个整数 X。查找数组中是否有一个三元组的总和为给定整数 X

问题描述

给定一个大小为 n 的数组 arr 和一个整数 X。找出数组中是否有一个三元组的总和等于给定的整数 X。

    Input:
        n = 5, X = 10
        arr[] = [1 2 4 3 6]
        
    Output:
        Yes
        
    Explanation:
        The triplet {1, 3, 6} in 
        the array sums up to 10.

标签: pythonarrays

解决方案


推理的路线是:获取数组 arr 中 3 个数字的所有可能组合。找出 sum=X 的,只打印这些三元组

import numpy as np
import itertools
arr=np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
X=10
combinations=np.array(list(itertools.combinations(arr, 3)))
triplets=combinations[combinations.sum(axis=1)==X]

print(f'Triplets with sum equal to {X} are:\n{triplets}')

输出:

Triplets with sum equal to 10 are:
[[0 1 9]
 [0 2 8]
 [0 3 7]
 [0 4 6]
 [1 2 7]
 [1 3 6]
 [1 4 5]
 [2 3 5]]

推荐阅读