@LIUHUAN
2020-01-12T10:24:15.000000Z
字数 2058
阅读 693
algorithm
int integerBreak(int n) {
//base case :just return for base case
if(n <= 0)
return 0;
if(n == 2 || n == 1)
return 1;
if(n == 3)
return 2;
return intbreak(n);
}
int intbreak(int n) {
if(n<=4)// case #1:the adder of sum
return n;
int r = 1;
for(int i = 1; i < n-1; i++){
int x = intbreak(n-i) * i;
r = max(r,x);
}
return r;
}
integerBreak
,对于小于4的情况,可以作为基本情况返回。intbreak
使用的是递归的调用,注意其递归的出口,小于4的情况,直接返回数。小于4的数作为因子,就是其本身。这里与integerBreak
不同,integerBreak
是分解后的结果。map
,也可以用数组,来缓存已经计算完的数据。对于已经获取的数据直接返回结果。
unordered_map<int,int> umap;
int integerBreak(int n) {
if(n <= 0)
return 0;
if(n == 2 || n == 1)
return 1;
if(n == 3)
return 2;
// base case for integer break as adder
for(int i = 1; i<= 4;i++) {
umap[i] = i;
}
return intbreak(n);
}
int intbreak(int n) {
if(umap.find(n) != umap.end()) {
return umap[n];
}
int r = 1;
for(int i=1; i < n-1; i++){
int x = intbreak(n-i) * i;
r = max(r,x);
}
umap[n] = r;
return r;
}
int integerBreak(int n) {
if(n <= 0)
return 0;
if(n == 2 || n == 1)
return 1;
if(n == 3)
return 2;
vector<int> dp(n+1,0);
// base case for adder n < 4
dp[1] = 1;
dp[2] = 2;
dp[3] = 3;
int x;
for(int i = 4; i <= n; i++ ) {
for(int k = i-1; k >= 1; k-- ) {
x = dp[k] * (i-k);
dp[i] = max(x,dp[i]);
}
}
return dp[n];
}
public int integerBreak(int n) {
if(n == 2) return 1;
if(n == 3) return 2;
int product = 1;
while( n > 4){
product *= 3;
n -= 3;
}
product *= n;
return product;
}