20200331——剑指offer 面试题14:割绳子

package question14_cut_rope;

/**
 * @Classname Solution1
 * @Description TODO
 * @Date 2020/3/31 21:41
 * @Created by mmz
 */
public class Solution1 {

    static int cutRope(int m){
        if(m<2){
            return 0;
        }
        if(m == 2){
            return 1;
        }
        if(m == 3){
            return 2;
        }
        int[] product = new int[m+1];
        product[0] = 0;
        product[1] = 1;
        product[2] = 2;
        product[3] = 3;


        int max;
        for(int i = 4;i<=m;++i){
            max = 0;
            for(int j = 1;j<=i/2;++j){
                int productcur = product[j]*product[i-j];
                if(productcur > max){
                   max = productcur;
                }
                product[i] = max;
            }
        }
        max = product[m];
        return max;

    }

    public static void main(String[] args) {
        System.out.println(cutRope(8));
    }
}

这次用到了动态规划的思想,f(n) = f(m)*f(m-n)


二刷
package question14_剪绳子;

/**
 * @Classname Main
 * @Description TODO
 * @Date 2020/4/11 17:04
 * @Created by mmz
 */
public class Main {
    static int Core(int length){
        if(length == 2){
            return 1;
        }
        if (length < 2) {
            return 0;
        }
        if(length == 3){
            return 2;
        }
        int[] lengths = new int[length+1];
        lengths[0] = 0;
        lengths[1] = 1;
        lengths[2] = 2;
        lengths[3] = 3;

        for(int i =4 ;i<= length ;i++){
            int max = 0;
            for(int j = 1;j<=i/2;j++){
                int curent = lengths[i-j]*lengths[j];
                if(curent > max){
                    max = curent;
                }
                lengths[i] = max;
            }
        }
        return lengths[length];
    }

    public static void main(String[] args) {
        System.out.println(Core(8));
    }
}

如果绳子的长度小于等于3,那么都是固定的。返回值不变。
当绳子大于等于4,以4来举列子,可以剪成1 3 或者 2 2 ,得到局部当前最大值的1 2 3 然后得到局部最大值的4,也就是说4的乘积最大为4
接着是5,每次遍历的i从3到长度,j的长度为一半。因为再往上就重复了。
比如5 = 2+3 =3 +2所以没有意义。到一半就可以结束了。

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值