剪绳子_动态规划法/贪心算法

1.思路:
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

动态规划法:
package jianzhi_offer;

public class cut_shengzi {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		int length = 3;
		int result = matProductAfterCutting_1(length);
		System.out.println(result);

	}
	
	private static int matProductAfterCutting_1(int length) {
		if(length < 2) {
			return 0;
		}
		if(length == 2) {
			return 1;
		}
		if(length == 3) {
			return 2;
		}
		
		//将最优解存储在数组中
		
		int[] products = new int[length+1];
		//数组中第i个元素表示把长度为i的绳子剪成若干段之后的乘积的最大值
		products[0] = 0;
		products[1] = 1;
		products[2] = 2;
		products[3] = 3;
		
		int max = 0;
		
		for(int i = 4; i <= length; i++) {
			max = 0;
			//求出所有可能的f(j)*f(i-j)并比较出他们的最大值
			for (int j = 1; j <= i/2; j++) {
				int product = products[j] * products[i-j];
				if(product > max) {
					max = product;
				}
				
				products[i] = max;
			}
		}
		
		max = products[length];
		return max;
	}

}

贪心算法
package jianzhi_offer;

public class cut_shengzi_2 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		int length = 8;
		int result = cutProp(length);
		System.out.println(result);
	}
	
	public static int cutProp(int length) {
		if(length < 2) {
			return 0;
		}
		if(length == 2) {
			return 1;
		}
		if(length == 3) {
			return 2;
		}
		
		int timeOf_3 = length/3;
		if(length - timeOf_3*3 == 1) {
			timeOf_3-=timeOf_3;
		}
		
		int timeOf_2 = (length - timeOf_3*3)/2;
		
		return (int)((Math.pow(3,timeOf_3))*(Math.pow(2,timeOf_2)));
	}
	
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值