算法作业_29(2017.6.12第十七周)
来源:互联网 发布:linux解压tar包命令 编辑:程序博客网 时间:2024/06/11 05:34
343. Integer Break
Given a positive integer n, break it into the sum of at least two positive integers and maximize the product of those integers. Return the maximum product you can get.
For example, given n = 2, return 1 (2 = 1 + 1); given n = 10, return 36 (10 = 3 + 3 + 4).
Note: You may assume that n is not less than 2 and not larger than 58.
解法一:递归的求解,n可以分解成: 1*(n-1),2*(n-2).......(n-1)*1。然后(n-1),(n-2),(n-3)...还可以继续分割下去,可以递归的求出,但是提交时会报错: Time Limit Exceeded:class Solution {public: int integerBreak(int n) { return breakInteger(n); } private: int breakInteger(int n ){ int res = -1; if(n==1) return 1; for(int i =1;i<=n-1;i++){ res = max3(res,i*breakInteger(n-i),i*(n-i)); } return res; } private: int max3(int a ,int b ,int c){ return max(a,max(b,c)); }};
解法二:记忆化搜索,上面的问题会导致内存溢出,是因为有大量的重复计算,所以我们可以在递归的时候记录已经计算过的值,并用数组存储起来,这样可以减少重复计算:AC
class Solution {public: int integerBreak(int n) { memo = vector<int>(n+1,-1); return breakInteger(n); } private: vector<int>memo; int breakInteger(int n ){ if(n==1) return 1; if(memo[n]!=-1) return memo[n]; int res = -1; for(int i =1;i<=n-1;i++){ res = max3(res,i*breakInteger(n-i),i*(n-i)); } memo[n] = res; return res; } int max3(int a ,int b ,int c){ return max(a,max(b,c)); }};
解法三:动态规划,将解法二进一步优化就是动态规划的思想:
class Solution { public: int integerBreak(int n) { vector<int> dp(n+1,-1); //dp[i]表示把数字i分割(至少分成两份)后的最大乘积 dp[1]=1; for(int i =2;i<=n;i++){ for(int j =1;j<=i-1;j++){ dp[i] = max3(dp[i],j*dp[i-j],j*(i-j)); } } return dp[n]; } private: int max3(int a ,int b ,int c){ return max(a,max(b,c)); }
343. Integer Break
阅读全文
0 0
- 算法作业_29(2017.6.12第十七周)
- 算法作业_30(2017.6.13第十七周)
- 算法作业_31(2017.6.14第十七周)
- 算法作业_32(2017.6.15第十七周)
- 算法第十七周作业01
- 算法课第十七周作业 | Same Tree
- 算法作业_33(2017.6.16第十七周)(算法机考模拟题1)
- 算法作业_34(2017.6.16第十七周)(算法机考模拟题2)
- 算法作业_35(2017.6.16第十七周)(算法机考模拟题3)
- 算法作业_36(2017.6.16第十七周)(算法机考模拟题5)
- 第十七周作业 1.0
- 第十七周作业1
- 第十七周作业
- 第十七周作业
- 算法设计与结构基础作业第十七周
- 第十七周算法题
- 第十七周LeetCode算法题
- 第十七周算法设计与分析:Minesweeper
- 记一次redis-cluster分别重启之后发生的问题
- Java-经典排序算法(一)
- 正则表达式贪婪与非贪婪模式
- AndroidStudio 插件 之 Findbugs 安装与简单使用教程
- 微信小程序——交互反馈 toast
- 算法作业_29(2017.6.12第十七周)
- Flexjson
- 关于centos7.2 升级Python之后yum报错的问题
- 动态 SQL
- linux自己创建守护进程
- 给eclipse 和tomcat增加内存步骤及报PermGen space错误
- 执行程序如何不一闪而过
- 新手闯GitHub,记录第一次推送项目到GitHub的操作
- 2. Add Two Numbers