状态计算 :
f[i]={cuboids[i][2]if 不存在kmax(f[k])+cuboids[i][2]if k∈[1,i−1]f[i] = \begin{cases} cuboids[i][2] &\text{if } 不存在k \\ max(f[k])+cuboids[i][2] &\text{if } k \in [1,i-1] \end{cases}f[i]={cuboids[i][2]max(f[k])+cuboids[i][2]if 不存在kif k∈[1,i−1]
其中 cuboids[i][2]cuboids[i][2]cuboids[i][2] 表示 iii 的高度。
设长方体 AAA 的宽长高为 w1,l1,h1w_1,l_1,h_1w1,l1,h1 ,BBB 的宽长高为 w2,l2,h2w_2,l_2,h_2w2,l2,h2
解题需要的性质 : 若 w1≤l1≤h1,w2≤l2≤h2w_1\le l_1 \le h_1,w_2\le l_2 \le h_2w1≤l1≤h1,w2≤l2≤h2 ,要 AAA 可以堆叠在 BBB 上,当且仅当 w1≤w2w_1\le w_2w1≤w2 且 l1≤l2l_1\le l_2l1≤l2 且 h1≤h2h_1\le h_2h1≤h2 。
证明 :
①满足 w1≤w2w_1\le w_2w1≤w2 且 l1≤l2l_1\le l_2l1≤l2 且 h1≤h2h_1\le h_2h1≤h2 ,一定是符合题意的堆叠方案。
②要证明仅当,可以反证,假设当 w1>w2w_1>w_2w1>w2 或 l1>l2l_1>l_2l1>l2 或 h1>h2h_1>h_2h1>h2 ,AAA 可以堆在 BBB 上,
综上,只有原命题成立,反证的结论才能成立,否则反证不成立。所以原命题成立。
class Solution {
public:int maxHeight(vector>& cuboids) {for(auto &c:cuboids) sort(c.begin(),c.end());sort(cuboids.begin(),cuboids.end());int n = cuboids.size();vector f(n,0);int ans = 0;for(int i = 0;if[i] = cuboids[i][2];for(int j = 0;j=cuboids[j][1]&&cuboids[i][2]>=cuboids[j][2])f[i] = max(f[i],f[j]+cuboids[i][2]);ans = max(ans,f[i]);}return ans;}
};