Given an array nums
of positive integers. Your task is to select some subset of nums
, multiply each element by an integer and add all these numbers. The array is said to be good if you can obtain a sum of 1
from the array by any possible subset and multiplicand.
Return True
if the array is good otherwise return False
.
Example 1:
Input: nums = [12,5,7,23]
Output: true
Explanation: Pick numbers 5 and 7.
5*3 + 7*(-2) = 1
Example 2:
Input: nums = [29,6,10]
Output: true
Explanation: Pick numbers 29, 6 and 10.
29*1 + 6*(-3) + 10*(-1) = 1
Example 3:
Input: nums = [3,6]
Output: false
Constraints:
1 <= nums.length <= 10^5
1 <= nums[i] <= 10^9
這道題給了一個正整數的數組 nums,定義了一種好數組,說是隨便從數組中選幾個數字,若可以通過乘以整數相加后得到1,則就是好數組,問給定的數組是否是好數組。這道題是一道 Hard 題目,而且是那種基於數學理論的題目,基本上就是若你沒有聽說過某個定理,那么基本上就是無法解出這道題目的。這道題考查的是貝祖等式,可以參見永樂老師的講解視頻,說的是對於任何整數 a, b 和 m 的方程 ax + by = m
有整數解的充要條件是m是a和b的最大公約數的倍數。這道題由於m是1,所以最大公約數必須是1。所以只要找到任意兩個數字的最大公約數是1即可,也就是可以找整個數組的最大公約數(因為整個數組的最大公約數不會大於任意兩個數字的最大公約數),明白了上面這些后,這道題就用幾行就可以搞定了,參見代碼如下:
class Solution {
public:
bool isGoodArray(vector<int>& nums) {
int res = nums[0];
for (int num : nums) {
res = gcd(res, num);
if (res == 1) return true;
}
return false;
}
};
Github 同步地址:
https://github.com/grandyang/leetcode/issues/1250
參考資料:
https://leetcode.com/problems/check-if-it-is-a-good-array/