NC281. 剪绳子
描述
输入描述
输入一个数n,意义见题面。输出描述
输出答案。示例1
输入:
8
输出:
18
说明:
8 = 2 +3 +3 , 2*3*3=18示例2
输入:
2
输出:
1
说明:
m>1,所以切成两段长度是1的绳子C++ 解法, 执行用时: 2ms, 内存消耗: 352KB, 提交时间: 2021-04-25
class Solution { public: int cutRope(int number) { int maxProduct = 0; if (number <= 3) return (number - 1); vector<int> dp(number + 1, 0); dp[1] = 1; dp[2] = 2; dp[3] = 3; for (int i = 4; i <= number; i ++) { for (int j = 1; j <= i / 2; j ++) maxProduct = max(maxProduct, dp[j] * dp[i - j]); dp[i] = maxProduct; } return dp[number]; } };
C++ 解法, 执行用时: 2ms, 内存消耗: 352KB, 提交时间: 2020-10-30
class Solution { public: int cutRope(int number) { if(number<=1) return 0; if(number==2) return 1; if(number==3) return 2; int length = number % 3 == 0 ? number / 3 : number / 3 + 1; int length1 = number % 3 == 0 ? 0 : 3 - number%3; int result=1; for(int i=0;i<length1;i++) { result=result*2; } for(int i=0;i<length-length1;i++){ result=result*3; } return result; } };
C++ 解法, 执行用时: 2ms, 内存消耗: 356KB, 提交时间: 2021-05-07
class Solution { public: int cutRope(int number) { int quotient( number>>1 ), remainder, tmp, res = quotient*(quotient+(number&1)); for(int i(3); i<=number; i++){ tmp = quotient = number/i; remainder = number%i; for(int j(remainder+1); j<i; j++) tmp *= quotient; quotient++; for(int k(0); k<remainder; k++) tmp *= quotient; if(tmp < res) return res; res = tmp; } return res; } };
C++ 解法, 执行用时: 2ms, 内存消耗: 356KB, 提交时间: 2021-05-06
class Solution { public: int cutRope(int number) { if(number == 2) return 1; if(number == 3) return 2; vector<int> f(number + 1, -1); for (int i = 1; i <= 4; ++i) { f[i] = i; } for (int i = 5; i <= number; ++i) { for (int j = 1; j < i; ++j) { f[i] = max(f[i], j * f[i - j]); } } return f[number]; } };
C++ 解法, 执行用时: 2ms, 内存消耗: 356KB, 提交时间: 2021-05-02
class Solution { public: int cutRope(int number) { if(number < 4) return number - 1; if(number == 4) return 4; int res = 1; while(number > 4){ res *= 3; number -= 3; } return res * number; } };