刷题-Leetcode-343. 整数拆分(动规)

343. 整数拆分

题目链接

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/integer-break/submissions/
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

题目描述

在这里插入图片描述

题目分析

当n=10
i=9时,j的取值范围[1,7]。
在这里插入图片描述注意:max函数的参数只能有两个。
dp[i]一定是拆分过的,最少两个数。

class Solution {
    
    
public:
    int integerBreak(int n) {
    
    
        vector<int> dp(n + 1);//第i个数拆分后最大值为dp[i] 
        dp[2] = 1;//初始化
        for(int i = 3; i <= n; i++){
    
    
            for(int j = 1; j < i - 1; j++){
    
    
                dp[i] = max(dp[i], max(j * dp[i - j], j * (i - j)));
            }
        }
        return dp[n];
    }
};

猜你喜欢

转载自blog.csdn.net/qq_42771487/article/details/118247216