51.和的逆运算问题|Marscode AI刷题

114 阅读2分钟

1.题目

问题描述

n 个整数两两相加可以得到 n(n - 1) / 2 个和。我们的目标是:根据这些和找出原来的 n 个整数。

按非降序排序返回这 n 个数,如果无解,输出 "Impossible"。


测试样例

样例1:

输入:n = 3, sums = [1269, 1160, 1663]

输出:"383 777 886"

样例2:

输入:n = 3, sums = [1, 1, 1]

输出:"Impossible"

样例3:

输入:n = 5, sums = [226, 223, 225, 224, 227, 229, 228, 226, 225, 227]

输出:"111 112 113 114 115"

样例4:

输入:n = 5, sums = [-1, 0, -1, -2, 1, 0, -1, 1, 0, -1]

输出:"-1 -1 0 0 1"

样例5:

输入:n = 5, sums = [79950, 79936, 79942, 79962, 79954, 79972, 79960, 79968, 79924, 79932]

输出:"39953 39971 39979 39983 39989"

2.思路

image.png

3.代码

import itertools
def solution(n, sums):
    # Please write your code here
    # 枚举 sums 的所有排列,一定会有一个排列是x1 + x2,x1 + x3,…,x1 + xn,x2 + x3, x2 + x4…
    for perm in itertools.permutations(sums):
        x1 = (perm[0] + perm[1] - perm[n - 1]) // 2

        # 利用 x1 来推导其他的 xi
        x = [x1]
        for i in range(n - 1):
            xi = perm[i] - x1
            x.append(xi)
        
        # 验证 xi 和 xj 是否满足所有 sums 条件
        index = 0
        valid = True
        for i in range(n):
            for j in range(i + 1, n):
                if x[i] + x[j] != perm[index]:
                    valid = False
                    break
                index += 1
            if not valid:
                break
        if valid:
            return " ".join(map(str, sorted(x)))
    # 如果所有排列都不满足,返回 "Impossible"
    return "Impossible"

if __name__ == "__main__":
    #  You can add more test cases here
    print(solution(3, [1269, 1160, 1663]) == "383 777 886")
    print(solution(3, [1, 1, 1]) == "Impossible")
    print(solution(5, [226, 223, 225, 224, 227, 229, 228, 226, 225, 227]) == "111 112 113 114 115")
    print(solution(5, [-1, 0, -1, -2, 1, 0, -1, 1, 0, -1]) == "-1 -1 0 0 1")
    print(solution(5, [79950, 79936, 79942, 79962, 79954, 79972, 79960, 79968, 79924, 79932]) == "39953 39971 39979 39983 39989")

4.参考资料

简单题:和的逆运算问题| 豆包MarsCode AI刷题-CSDN博客