码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode刷题,总结,记录,备忘 343

时间:2016-05-13 02:09:09      阅读:138      评论:0      收藏:0      [点我收藏+]

标签:

leetcode343Integer 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.

Show Hint 

Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.

Subscribe to see which companies asked this question

使用动态规划,通过观察我们可以发现一个规律,n的最大值要么是在n-1的基础上再加上一个1,要么是在n-2的基础上加上2.首先如果是以n-1的结果为基础,如果单纯加一个1在n-1的数组中,结果是不变的,所以需要在n-1的数组中的某个元素上加1,这个1最好加在n-1的数组中的最小的数上,这样得到的乘积才是最大的。如果以n-2为基础的话,直接在n-2的数组中加个2即可,然后在这2个数组中计算结果最大的那个就是n的结果。假设dp这个数组是保存每个数字的各个数字的数组,比如dp[10] = {3, 3, 4}。在递归公式之前需要做的工作,dp[n - 2].push_back(2); sort(dp[n - 2].begin(), dp[n - 2].end()); dp[n  - 1][0]++ ;  sort(dp[n - 1].begin(), dp[n - 1].end());  递归公式: dp[n] = func(dp[n - 2]) > func(dp[n - 1]) ? dp[n - 2] : dp[n - 1];  func是一个计算数组结果的辅助函数,对数组做排序是为了服务于之后的计算。具体可以查看代码。

class Solution {
public:
    int function(vector<int> t)
    {
        int sum = 1;
        for (int i = 0; i < t.size(); ++i)
        {
            sum *= t[i];
        }
        
        return sum;
    }

    int integerBreak(int n) {
        if (n <= 0)
        {
            return 0;
        }
        
        if (n == 1)
        {
            return 1;
        }
        
        vector<vector<int> > dp(n + 1, vector<int>());
        
        dp[1].push_back(1);
        dp[2].push_back(1);
        dp[2].push_back(1);
        
        for (int i = 3; i < dp.size(); ++i)
        {
            vector<int> temp1 = dp[i - 2];
            temp1.push_back(2);
            vector<int> temp2 = dp[i - 1];
            temp2[0]++;
            sort(temp1.begin(), temp1.end());
            sort(temp2.begin(), temp2.end());
            
            if (function(temp1) > function(temp2))
            {
                dp[i] = temp1;
            }
            else
            {
                dp[i] = temp2;
            }
        }
        
        return function(dp[n]);
        
    }
};


leetcode刷题,总结,记录,备忘 343

标签:

原文地址:http://blog.csdn.net/guicaisa/article/details/51347610

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!