https://leetcode.com/problems/patching-array/description/
https://discuss.leetcode.com/topic/45320/c-8ms-greedy-solution-with-explanation
解题思路来自@Dragon.PW,表示感谢!
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:
nums = [1, 3], n = 6
Return 1.
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.
分析
最直接的解法就是枚举对比加最小
先对升序数组求全子集数组,对每个子集求和,排序对比范围,添加未能取得的最小值,更新子集数组…直到取得目标范围
在目标取值非常大的情况下,因为要持续维护子集数组,内存就爆了
事实上每次取最小值的过程就是一个贪心的过程,要是从0开始,选择最小值的策略则变成当前nums中的最小值在maxRange内则取nums中的值,否则添加新元素maxRange+1,这样就能确保在当前基础上最大的覆盖取值范围,也就使得添加的元素最少了。
const minPatches = (nums, n) => {
let i = 0;
let res = 0;
let maxRange = 0;
while (maxRange < n) {
if (i < nums.length && nums[i] <= maxRange+1) {
maxRange += nums[i++];
} else {
maxRange += maxRange+1;
res++;
}
}
return res;
}
之前绕了一圈,代码也贴上吧
const getSubSets = (arr, pos) => {
let res = [];
if (pos >= arr.length) {
const temp = []
res.push(temp);
return res;
}
let res2 = getSubSets(arr, pos+1);
const len = res2.length;
for (let i = 0; i < len; ++i) {
const temp = res2[i].map(item => item);
temp.push(arr[pos]);
res2.push(temp);
}
return res2;
}
var minPatches2 = function(nums, n) {
const cover = [];
for (let i = 1; i <= n; ++i) {
cover.push(i);
}
const subSets = getSubSets(nums, 0);
let mapping = subSets.map((set) => {
return set.reduce((pre, next) => {
return pre + next;
}, 0);
});
mapping.sort((a, b)=>{return a-b});
console.log(mapping);
let res = 0;
let rest = cover.filter((item) => {
return mapping.indexOf(item) == -1;
})
console.log(rest);
while (rest.length) {
res++;
let len = mapping.length;
for (let i = 0; i < len; ++i) {
mapping.push(mapping[i] + rest[0]);
}
mapping.sort((a, b)=>{return a-b});
len = mapping.length;
temp = [mapping[0]];
for (let i = 1; i < len; ++i) {
if (mapping[i] == mapping[i-1]) {
continue;
}
temp.push(mapping[i]);
}
mapping = null;
mapping = temp;
rest = rest.filter((item) => {
return mapping.indexOf(item) == -1;
});
}
return res;
};