Topics are as follows:
Given an array
nums
of positive integers. Your task is to select some subset ofnums
, multiply each element by an integer and add all these numbers. The array is said to be good if you can obtain a sum of1
from the array by any possible subset and multiplicand.Return
True
if the array is good otherwise returnFalse
.Example 1:
Input: nums = [12,5,7,23] Output: true Explanation: Pick numbers 5 and 7. 5*3 + 7*(-2) = 1Example 2:
Input: nums = [29,6,10] Output: true Explanation: Pick numbers 29, 6 and 10. 29*1 + 6*(-3) + 10*(-1) = 1Example 3:
Input: nums = [3,6] Output: falseConstraints:
1 <= nums.length <= 10^5
1 <= nums[i] <= 10^9
Problem-solving ideas: See this subject, we might be able to guess this question corresponds to mathematical laws. As to what the law is, I do not know. Later, the Internet search found a corresponding law is Shu Pei theorem, the final solution is to find the common denominator of all the elements, you can determine whether 1.
Shu Pei Theorem (or Bezu Theorem , Bézout's identity) is named after the French mathematician Etienne Pei Shu, it describes any integer , b, and their largest convention a The number of d, on the unknowns of Indeterminate Equation x and y (referred to as PEI Shu equation): if a, b are integers and gcd (a, b) = d , then for any integers x, y, ax + by must be a multiple of d are, in particular, certain integers x, y, ax + by = d so established.
code show as below:
class Solution(object): def isGoodArray(self, nums): """ :type nums: List[int] :rtype: bool """ def gcd(m, n): if not n: return m else: return gcd(n, m % n) val = nums[0] for i in range(1,len(nums)): val = gcd(val,nums[i]) return val == 1