https://leetcode.com/problems/fair-distribution-of-cookies/description/
2305. Fair Distribution of Cookies
给你一个阵列 cookies[],cookies[i] 表示每个袋子里的饼干数量,袋子里的饼干
不可以拆分,我们要把饼干分给 k 个小孩,每个小孩需要拿至少一袋,不公平度
被定义成每个小孩的饼干数量中取最大,求出最小的不公平度。
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.
思路:
1.先从穷举开始想,饼干有 n 个分给 k 个小孩,每个饼干有 k 种分法,所以共有
k^n 种分法,题目的 n 和 k 最多为 8 ,还可以接受用 DFS 穷举。
2.假定饼干结构为 [3, 2, 1] 且 k = 2 ,cnt[] 定义为每个小孩的饼干数量,则所有
的分配结果如下:
左:该小孩拿饼干
右:该小孩不拿饼干
cnt = [0,0] _______________
/ \
饼干一 [3,0] [0,3]
/ \ / \
饼干二 [5,0] [3,2] [2,3] [0,5]
/ \ / \ / \ /\ / \ / \
饼干三 [6,0] [5,1][4,2][3,3] [3,3][2,4] [1,5][0,6]
将最后一个饼干分配完之后的 cnt 取最大元素后,再把每个结果最大元素取最小值
就是答案了(3, 3)
3.观察上树我们可以发现,右边的回溯树就是左边的反方向(只有顺序不同),当我们
发第一个饼干的时候无论是给哪一个小孩,产生的树都会是一样的结构,只有饼干顺序
不同不会产生比先前更优的解,所以我们可以检查当前面的小孩没有拿到饼干时,他后
面长出来的树就可以不用看了。
Java Code: