LeetCode 343. Integer Break

来源:互联网 发布:李易峰睡杨幂 知乎 编辑:程序博客网 时间:2024/06/05 03:36

题目:
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.

思路1:先说第一种 暴力方法。。。反正就是暴力 没啥优势。。。直接进行搜索比较找出最大的,从小到大开始计算,其实也算是用了一点点动态规划了,因为对比了j和a[j]的大小值。

代码:

class Solution {public:    int integerBreak(int n) {        int a[59] = { 0, 1, 1, 2, 4 };        for (int i = 5; i < 59; ++i){            a[i] = i;        }//a初始化        int max;        int tmp1;        int tmp2;        int tmp3;        for (int i = 2; i < 59; ++i){            max = a[i];            tmp1 = a[i] - 1;//记录最后一个数            for (int j = 1; j <= tmp1; ++j, --tmp1){                tmp2 = a[j] > j ? a[j] : j;//分别初始化tmp2和tmp3,同理,当前值和索引中更大的那个                tmp3 = a[tmp1] > tmp1 ? a[tmp1] : tmp1;                max = max > tmp2 * tmp3 ? max : tmp2*tmp3;//对比 max 和 tmp2*tmp3 的大小,取大的            }            a[i] = max;        }        return a[n];    }};

输出结果: 0ms

思路2:网上找的,因为当n为4时,最大值就和本身相等,所以,当n<=3时,3这个值为最大,所以计算integerBreak的最大值,也就是计算integerBreak(n-3)的最大值,也就有了integerBreak=3*integerBreak(n-3),但又要保证n-3>3,所以计算到了6。

代码2:

class Solution {public:    long long integerBreak(long long n) {        if(n == 2) return 1;        if(n == 3) return 2;        if(n == 4) return 4;        if(n == 5) return 6;        if(n == 6) return 9;        return 3 * integerBreak(n - 3);    }};

输出结果2: 0ms