杆子分割

编程入门 行业动态 更新时间:2024-10-11 01:10:27

<a href=https://www.elefans.com/category/jswz/34/1748734.html style=杆子分割"/>

杆子分割

给一个 n 英寸长的杆子和一个包含所有小于 n 的尺寸的价格. 确定通过切割杆并销售碎片可获得的最大值.例如,如果棒的长度为8,并且不同长度部件的值如下,则最大可获得值为 22(通过切割两段长度 2 和 6 )

您在真实的面试中是否遇到过这个题?   是

样例

长度    | 1   2   3   4   5   6   7   8  
--------------------------------------------
价格    | 1   5   8   9  10  17  17  20

给出 price = [1, 5, 8, 9, 10, 17, 17, 20], n = 8 返回 22//切成长度为 2 和 6 的两段

长度    | 1   2   3   4   5   6   7   8  
--------------------------------------------
价格    | 3   5   8   9  10  17  17  20

给出 price = [3, 5, 8, 9, 10, 17, 17, 20], n = 8 返回 24//切成长度为 1 的 8 段


two solution: 1 er wei qujian DP; 2 duplicate backpack

class Solution {
public:/** @param : the prices* @param : the length of rod* @return: the max value*/int cutting(vector<int>& prices, int n) {// Write your code hereif (prices.size() != n) {return 0;}if (n == 1) {return prices[0];}vector<int> cut_maxs(n + 1, 0);// initcut_maxs[1] = prices[0];for (int i = 2; i <= n; i++) {int max_cut = prices[i - 1];// no cutfor (int j = 1; j <= i/2; j++) {max_cut = max(cut_maxs[j] + cut_maxs[i - j], max_cut);}cut_maxs[i] = max_cut;}return cut_maxs[n];}};

class Solution {
public:/*** @param prices: the prices* @param n: the length of rod* @return: the max value*/int cutting(vector<int> &prices, int n) {// Write your code hereif (prices.size() != n || n == 0) {return 0;}vector<int> dp(n + 1, 0);for (int i = 1; i <= n; i++) {for (int j = 1; j <= n; j++) {if (j >= i) {dp[j] = max(prices[i - 1] + dp[j - i], dp[j]);}}}return dp[n];}
};



更多推荐

杆子分割

本文发布于:2024-02-06 10:39:05,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1748473.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:杆子

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!