题目描述
Given a sorted positive integer array nums and an integer n, add/patch elements to the array such that any number in range [1, n]
inclusive can be formed by the sum of some elements in the array. Return the minimum number of patches required.
Example 1:
Input: nums = [1,3], n = 6
Output: 1
Explanation:
Combinations of nums are [1], [3], [1,3], which form possible sums of: 1, 3, 4.
Now if we add/patch 2 to nums, the combinations are: [1], [2], [3], [1,3], [2,3], [1,2,3].
Possible sums are 1, 2, 3, 4, 5, 6, which now covers the range [1, 6].
So we only need 1 patch.
Example 2:
Input: nums = [1,5,10], n = 20
Output: 2
Explanation: The two patches can be [2, 4].
Example 3:
Input: nums = [1,2,2], n = 5
Output: 0
题意:给定一个已排序的正整数数组nums
,和一个正整数n
。从 [1, n]
区间内选取任意个数字补充到nums
中,使得[1, n]
区间内的任何数字都可以用 nums
中某几个数字的和来表示。请输出满足上述要求的最少需要补充的数字个数。
算法1
(贪心)
题解:假设我们已经可以生成[0,miss)
之间的所有数字了,那么我们必须添加一个数来辅助生成miss
,准备添加的数字一定要小于等于x <= miss
,否则的话我们还是无法生成miss
。那么因为我们已经能够生成了[0,miss)
间的数字了,那么加上一个数x
后,我们能够生成的数字范围是[0,miss + x)
的,又根据贪心的思想,我们每次加的数最好能使得区间变得尽可能大,所以我们应该加入miss
这个数。另一方面,如果我们可以利用nums
数组中的数来辅助生成miss
,对于一个nums[i] < miss
,如果我们选择加入这个数,那么我们可以将区间扩张为[0,nums[i] + miss)
,而不用新增额外的数。所以我们的算法思路如下:
- 假设当前我们能生成的数字为
[0,miss)
,如果nums[i]
存在小于等于miss
的数,那么我们先选择添加这个数并将我们的miss = miss + nums[idx]
。 - 如果不存在的话,那么说明我们需要自己添加一个新数了,我们选择加入
miss
,所以miss = miss + miss
,同时记录答案。
int minPatches(vector<int>& nums, int n) {
int res = 0,idx = 0,m = nums.size();
long long miss = 1;
while(miss <= n)
{
if(idx < m && miss >= nums[idx])
miss += nums[idx ++];
else
{
miss = miss << 1;
res ++;
}
}
return res;
}
这种贪心到底怎么才能想到!
靠不断的刷题找灵感