剪绳子

/*
 * 给你一根长度为n绳子,请把绳子剪成m段(m、n都是整数,n>1并且m≥1)。
 * 每段的绳子的长度记为k[0]、k[1]、……、k[m]。k[0]* k[1]*……*k[m]可能的最大乘积是多少?
 * 例如当绳子的长度是8时,我们把它剪成长度分别为2、3、3的三段,此 时得到最大的乘积18。
 */
public class CutRope {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Scanner scanner = new Scanner(System.in);
		int n = scanner.nextInt();
		int product = maxProduct(n);
		System.out.println(product);
		
	}
	static int f(int n) {//递归解法  重复率高
		if( n == 1) {
			return 1;
		}
		if( n == 2) {
			return 2;
		}
		if(n == 3) {
			return 3;
		}
		int max1 = 0;
		for( int i = 4; i <= n; i++) {
			for( int j = 1; j <= i/2; j++) {
				if(max1 < f(i-j)*f(j)) {
					max1 = f(i-j)*f(j);
				}
			}

		}
		return max1;
	}
	static int maxProduct(int length) { //动态规划
		if(length < 2) {
			return 0;
		}
		if(length == 2) {
			return 1;
		}
		if(length == 3) {
			return 2;
		}
		int products[] = new int[length+1];
		products[0] = 0;
		products[1] = 1;
		products[2] = 2;
		products[3] = 3;
		for(int i = 4; i <= length; i++) {
			for(int j = 1; j <= i/2; j++) {
				int product = products[j] * products[i-j];
				if(product > products[i]) {
					products[i] = product;
				}
			}
		}
		return products[length];
	}

}

### 贪心算法实现 贪心算法的思路是尽可能多地长度为3的绳子段,因为当绳子长度大于等于5时,长度为3的段可以获得更大的乘积。当剩下的长度为4时,将其成两个2的段,这样可以获得更大的乘积[^2]。 ```cpp #include <iostream> #include <cmath> class Solution { public: int cutRope(int number) { if(number < 2) return 0; if(number == 2) return 1; if(number == 3) return 2; int countOf3 = number / 3; if (number - countOf3 * 3 == 1) { countOf3--; return static_cast<int>(pow(3, countOf3)) * 4; } if (number - countOf3 * 3 == 2) { return static_cast<int>(pow(3, countOf3)) * 2; } return static_cast<int>(pow(3, countOf3)); } }; int main() { Solution sol; std::cout << sol.cutRope(10) << std::endl; // 输出 36 return 0; } ``` ### 动态规划实现 动态规划的思路是将绳子长度从1到n的所有可能法都计算出来,并存储在数组中。对于每个长度i,遍历所有可能的法j(从1到i-1),并计算j*(i-j)和dp[j]*(i-j)的乘积,取最大值作为dp[i]的值[^1]。 ```cpp #include <iostream> #include <vector> #include <algorithm> class Solution { public: int cutRope(int number) { if (number < 2) return 0; if (number == 2) return 1; if (number == 3) return 2; std::vector<int> dp(number + 1, 0); for (int i = 1; i <= number; ++i) { for (int j = 1; j < i; ++j) { dp[i] = std::max(dp[i], std::max(j * (i - j), j * dp[i - j])); } } return dp[number]; } }; int main() { Solution sol; std::cout << sol.cutRope(10) << std::endl; // 输出 36 return 0; } ``` ### 总结 - **贪心算法**:适用于较大的绳子长度,时间复杂度为O(1),但需要数学推导来证明最优解。 - **动态规划**:适用于较小的绳子长度,时间复杂度为O(n^2),但不需要数学推导。 两种方法都可以有效地解决绳子问题,选择哪种方法取决于具体的应用场景和对时间复杂度的要求。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值