问题:
给定一组数,将其分配给多个用户,
每个用户要求quantity[i]个相同的数。
问是否能够分配完。
Example 1: Input: nums = [1,2,3,4], quantity = [2] Output: false Explanation: The 0th customer cannot be given two different integers. Example 2: Input: nums = [1,2,3,3], quantity = [2] Output: true Explanation: The 0th customer is given [3,3]. The integers [1,2] are not used. Example 3: Input: nums = [1,1,2,2], quantity = [2,2] Output: true Explanation: The 0th customer is given [1,1], and the 1st customer is given [2,2]. Example 4: Input: nums = [1,1,2,3], quantity = [2,2] Output: false Explanation: Although the 0th customer could be given [1,1], the 1st customer cannot be satisfied. Example 5: Input: nums = [1,1,1,1,1], quantity = [2,3] Output: true Explanation: The 0th customer is given [1,1], and the 1st customer is given [1,1,1]. Constraints: n == nums.length 1 <= n <= 105 1 <= nums[i] <= 1000 m == quantity.length 1 <= m <= 10 1 <= quantity[i] <= 105 There are at most 50 unique values in nums.
解法:Backtracking(回溯算法)
状态:第pos个用户,被分配的数字。
选择:数字中个数>=该pos用户要求的个数,的所有数字选择。
递归退出条件:pos==用户数quantity.size
⚠️ 注意:简单的回溯,会导致超时。
因此将用户要求按数字多的->少的进行DESC降序排序,首先满足要求多的。
代码参考:
1 class Solution { 2 public: 3 // int count = 0; 4 // void print_intend() { 5 // for(int i=0; i<count; i++) 6 // printf(" "); 7 // } 8 void backtrack(bool& res, int pos, vector<int>& quantity, vector<int>& nc) { 9 if(pos==quantity.size()) { 10 // print_intend(); 11 // printf("return true\n"); 12 res = true; 13 return; 14 } 15 // int idx = lower_bound(nc.begin(), nc.end(), quantity[pos])-nc.begin(); 16 // print_intend(); 17 // printf("lower_bound idx:[%d]\n",idx); 18 //for(int i=idx; i<nc.size(); i++) { 19 for(int i=0; i<nc.size(); i++) { 20 if(nc[i]<quantity[pos]) continue; 21 nc[i]-=quantity[pos]; 22 // count++; 23 // print_intend(); 24 // printf("pos:%d, idx:%d, nc[998]:%d ,nc[999]:%d\n", pos, i, nc[998], nc[999]); 25 backtrack(res, pos+1, quantity, nc); 26 // count--; 27 nc[i]+=quantity[pos]; 28 if(res==true) return; 29 } 30 //print_intend(); 31 //printf("return [try all finished]\n"); 32 return; 33 } 34 bool canDistribute(vector<int>& nums, vector<int>& quantity) { 35 bool res = false; 36 vector<int> nc; 37 unordered_map<int, int> ncount; 38 for(int n:nums) { 39 ncount[n]++; // count 40 } 41 for(auto nct:ncount) { 42 nc.push_back(nct.second); 43 } 44 sort(quantity.rbegin(), quantity.rend()); 45 backtrack(res, 0, quantity, nc); 46 return res; 47 } 48 };