動態規劃之發現重疊子問題 LeetCode 343 整數拆分

當遇到一個問題,想要使用動態規劃的基礎是發現重疊子問題

以LeetCode 343 整數拆分 這道題爲例

題目

給定一個正整數 n,將其拆分爲至少兩個正整數的和,並使這些整數的乘積最大化。 返回你可以獲得的最大乘積。
示例 1:
輸入: 2
輸出: 1
解釋: 2 = 1 + 1, 1 × 1 = 1。
示例 2:
輸入: 10
輸出: 36
解釋: 10 = 3 + 3 + 4, 3 × 3 × 4 = 36。
說明: 你可以假設 n 不小於 2 且不大於 58。

思路

我們解這道題,可以使用遞歸樹

對於這棵遞歸樹,顯然有很多重疊的子問題

最優子結構:通過求子問題的最優解,可以獲得原問題的最優解

對於一個問題來說,如果在遞歸結構中發現了很多重疊子問題,其實就可以使用動態規劃了

 

解法1:遞歸

注意,當前數n可以將其分割成i*(n-i) 或者i*分割(n-i)的最大乘積

#include <iostream>
#include <vector>
using namespace std;
//遞歸解 
class Solution { 
public:
	
	//拆解n的最大乘積 
    int integerBreak(int n) {
		if(n==1) return 1; 
		if(n==2) return 1;
		//可以將n拆解爲1---n-1 * 剩下數拆解的最大乘積 ,求其中結果最大值 
		int res = -1; 
		for(int i=1; i<n; i++) 
		{
			res = max3(res,i*(n-i), i*integerBreak(n-i));//注意,這邊可以將n拆成i和n-i也需要考慮 
		} 
		return res; 
    }
    int max3(int a,int b, int c)
    {
    	return max(a,max(b,c));
    }
};
int main()
{
	cout<<Solution().integerBreak(28); 
	return 0;
}

解法2:記憶化搜索

#include <iostream>
#include <vector>
using namespace std;

//遞歸+記憶化搜索解 
class Solution { 
public:
	vector<int> memo;
	//拆解n的最大乘積 
	int Break(int n)
	{
		if(n==1) return 1; 
		if(n==2) return 1;
		//可以將n拆解爲1---n-1 * 剩下數拆解的最大乘積 ,求其中結果最大值 
		if(memo[n]!=-1) return memo[n];
		int res = -1; 
		for(int i=1; i<n; i++) 
		{
			res = max3(res,i*(n-i), i*integerBreak(n-i));//注意,這邊可以將n拆成i和n-i也需要考慮 
		} 
		memo[n]= res;
		return res; 
	}
	
    int integerBreak(int n) {
		memo = vector<int>(n+1,-1); 
		return Break(n);
    }
    int max3(int a,int b, int c)
    {
    	return max(a,max(b,c));
    }
};
int main()
{
	cout<<Solution().integerBreak(28); 
	return 0;
}

解法3:動態規劃

#include <iostream>
#include <vector>
using namespace std;

//動態規劃解 
class Solution { 
public:
    int integerBreak(int n) {
		vector<int> memo(n+1,-1); //memo[i]中存儲拆分i的最大乘積 
		memo[1]=1;
		for(int i=2; i<=n; i++) 
		{
			for(int j=1; j<i; j++) //拆分i的所有可能性
			{
				memo[i] = max3(memo[i],j*(i-j),j*memo[i-j]);
			} 
		}
		return memo[n];
    }
    int max3(int a,int b, int c)
    {
    	return max(a,max(b,c));
    }
};
int main()
{
	return 0;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章