剪绳子 --剑指offer

题目描述

给你一根长度为n的绳子,请把绳子剪成整数长的m段(m、n都是整数,n>1并且m>1),每段绳子的长度记为k[0],k[1],...,k[m]。请问k[0]xk[1]x...xk[m]可能的最大乘积是多少?例如,当绳子的长度是8时,我们把它剪成长度分别为2、3、3的三段,此时得到的最大乘积是18。
 
思路:尽可能多的剪成长度3的绳子 然后建成2的  有一点注意的是 如果剩4的话 建成2*2 比 3*1 好
public class Solution {
    public int cutRope(int target) {
        if(target <= 1) return 0;
        if(target == 2) return 1;
        if(target == 3) return 2;
        int x=target/3;
        int y=target%3;
        if(y == 1) {
            return 4*(int)Math.pow(3,x-1);
        }
        else if(y == 2){
            return 2*(int)Math.pow(3,x);
        }else {
            return (int)Math.pow(3,x);
        }
    }
}

 动态规划也可以

将这个长度分为两半 当前长度乘积最大就等于两半分别的乘积最大  -》最优子结构和子问题重叠 

public class Solution {
    public int cutRope(int target) {
        if(target <= 1) return 0;
        if(target == 2) return 1;
        if(target == 3) return 2;
        int[] project=new int[target+1];
        project[0]=0;
        project[1]=1;
        project[2]=2;
        project[3]=3;
        for(int i = 4;i <= target;i ++){
            int max=0;
            for(int j = 1;j <= i/2;j ++){
                max=Math.max(max,project[j]*project[i-j]);
            }
            project[i] = max;
        }
        return project[target];
    }
}
原文地址:https://www.cnblogs.com/nlw-blog/p/12483911.html