You are given an integer array matchsticks where matchsticks[i] is the length of the ith matchstick. You want to use all the matchsticks to make one square. You should not break any stick, but you can link them up, and each matchstick must be used exactly one time.
Return true if you can make this square and false otherwise.
Example 1:
img
Input: matchsticks = [1,1,2,2,2]
Output: true
Explanation: You can form a square with length 2, one side of the square came two sticks with length 1.
Example 2:
Input: matchsticks = [3,3,3,3,4]
Output: false
Explanation: You cannot find a way to form a square with all the matchsticks.
You are given an integer array cookies, where cookies[i] denotes the number of cookies in the ith bag. You are also given an integer k that denotes the number of children to distribute all the bags of cookies to. All the cookies in the same bag must go to the same child and cannot be split up.
The unfairness of a distribution is defined as the maximumtotal cookies obtained by a single child in the distribution.
Return the minimum unfairness of all distributions.
Example 1:
Input: cookies = [8,15,10,20,8], k = 2
Output: 31
Explanation: One optimal distribution is [8,15,8] and [10,20]
- The 1st child receives [8,15,8] which has a total of 8 + 15 + 8 = 31 cookies.
- The 2nd child receives [10,20] which has a total of 10 + 20 = 30 cookies.
The unfairness of the distribution is max(31,30) = 31.
It can be shown that there is no distribution with an unfairness less than 31.
Example 2:
Input: cookies = [6,1,3,2,2,4,1,2], k = 3
Output: 7
Explanation: One optimal distribution is [6,1], [3,2,2], and [4,1,2]
- The 1st child receives [6,1] which has a total of 6 + 1 = 7 cookies.
- The 2nd child receives [3,2,2] which has a total of 3 + 2 + 2 = 7 cookies.
- The 3rd child receives [4,1,2] which has a total of 4 + 1 + 2 = 7 cookies.
The unfairness of the distribution is max(7,7,7) = 7.
It can be shown that there is no distribution with an unfairness less than 7.
Constraints:
2 <= cookies.length <= 8
1 <= cookies[i] <= 105
2 <= k <= cookies.length
这个和上面的那道题差不多,不过这个回溯的时候不需要条件,只需要在结束处比较获得答案
class Solution {int n;// number of cookies bagsint kk;// number of childerint ans =1e6;// final answer, initial big valuevoid dfs(int index, vector<int>& cookies, vector<int>& bucket){if(index == n){// when the cookies distributie over ans = min(ans,*max_element(bucket.begin(), bucket.end()));// renew answerreturn;}// optimize: if one child get more cookie than answerfor(int i =0; i < kk; i++){if(bucket[i]> ans){return;}}for(int i =0; i < kk; i++){// core code bucket[i]+= cookies[index]; dfs(index+1, cookies, bucket); bucket[i]-= cookies[index];}return;}public:int distributeCookies(vector<int>& cookies,int k){ n = cookies.size(); kk = k; vector<int>bucket(k,0);// optimize, push greater number in front sort(cookies.begin(), cookies.end(), greater<int>()); dfs(0, cookies, bucket);return ans;}};