343 整数拆分

(1)第一种方法:递归加记忆化搜索

class Solution {
public:
	vector memo;
	int max3(int a, int b, int c){
		
		return max(a, max(b,c));
	}
	int dfs(int n){
		if (n == 1) return 1;
		int res = -1;
		if (memo[n] != -1)
			return memo[n];
		for (int i = 1; i <= n - 1; i++)
			 res = max3(res, i*(n - i), i*dfs(n - i));
			 memo[n] = res;
			 return res;
		
		

	}
	int integerBreak(int n) {
		memo = vector(n+1, -1);
		return dfs(n);
	}
};


int main(){
	int n = 4;
	Solution solution;
	int res = solution.integerBreak(n);
	return 0;
}

(2)第二种方法:动态规划

class Solution {
public:
	int max3(int a, int b, int c){
		return max(max(a, b), c);
	}
	int integerBreak(int n) {
		vectormemo(n+1, -1);
		memo[1] = 1;
		for (int i = 2; i <= n; i++){
			for (int j = 1; j <= i - 1; j++){
				memo[i] = max3(memo[i], j*(i - j), j*memo[i - j]);
			}//如果memo已经赋值,那么它肯定是三者最大的,如果没被赋值,那么其为-1,
		}    //这一步就是在计算它。
		return memo[n];
	}
};

 

你可能感兴趣的:(Leetcode刷题)