leetcode 330. Patching Array

- 日理万妓 2022-08-20 10:26 81阅读 0赞

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.

Example 2:
nums = [1, 5, 10], n = 20
Return 2.
The two patches can be [2, 4].

Example 3:
nums = [1, 2, 2], n = 5
Return 0.

  1. #include "stdafx.h"
  2. #include<vector>
  3. #include<set>
  4. #include<iterator>
  5. #include<algorithm>
  6. #include<iostream>
  7. using namespace std;
  8. class Solution {
  9. public:
  10. set<set<int>>solu;
  11. void select(set<int>&selected, vector<int>&remain, int toselect)
  12. {
  13. if (selected.size() == toselect)
  14. {
  15. if (solu.find(selected) == solu.end())
  16. {
  17. solu.insert(selected);
  18. }
  19. return;
  20. }
  21. for (int i = 0; i < remain.size(); i++)
  22. {
  23. vector<int> re = remain;
  24. set<int>se = selected;
  25. se.insert(re[i]);
  26. re.erase(re.begin() + i);
  27. select(se, re, toselect);
  28. }
  29. }
  30. void Combination(int len, int toselect)//组合
  31. {
  32. solu.clear();
  33. vector<int>remain;
  34. set<int>selected;
  35. for (int i = 1; i <= len; i++)
  36. remain.push_back(i);
  37. select(selected, remain, toselect);
  38. cout << "共有" << solu.size() << "种组合" << endl;
  39. }
  40. int minPatches(vector<int>& nums, int n) {
  41. set<int>mynum, allnums,re;
  42. vector<int>toinsert;
  43. for (int i = 1; i <= n; i++)
  44. allnums.insert(i);
  45. while (true)
  46. {
  47. for (int i = 1; i <= nums.size(); i++)
  48. {
  49. Combination(nums.size(), i);
  50. for (set<set<int>>::iterator it = solu.begin(); it != solu.end(); it++)
  51. {
  52. int sum = 0;
  53. for (set<int>::iterator iter = it->begin(); iter != it->end(); iter++)
  54. {
  55. sum += nums[*iter - 1];
  56. }
  57. mynum.insert(sum);
  58. }
  59. }
  60. re.clear();
  61. set_difference(allnums.begin(), allnums.end(), mynum.begin(), mynum.end(), inserter(re, re.begin()));
  62. if (re.empty())
  63. return toinsert.size();
  64. nums.push_back(*re.begin());
  65. toinsert.push_back(*re.begin());
  66. mynum.clear();
  67. }
  68. }
  69. };
  70. int _tmain(int argc, _TCHAR* argv[])
  71. {
  72. vector<int>nums;
  73. nums.push_back(1);
  74. nums.push_back(3);
  75. //nums.push_back(10);
  76. Solution sl;
  77. cout<<sl.minPatches(nums, 6);
  78. //.Combination(100,40);
  79. system("pause");
  80. return 0;
  81. }

发表评论

表情:
评论列表 (有 0 条评论,81人围观)

还没有评论,来说两句吧...

相关阅读