剪绳子

剪绳子

http://www.nowcoder.com/questionTerminal/57d85990ba5b440ab888fc72b0751bf8

1 递归

public class Solution {
    public int cutRope(int target) {
        if(target < 4)
            return target-1;
        return getMax(target);
    }
    public int getMax(int target){
        if(target < 4)
            return target;
        int n1 = 2 * (target-2);
        int n2 = 3 * (target-3);
        return n2 > n1 ? n2 : n1;
    }
}

通过递归可以很容易看出,最后的结果就是x个3和y个2相乘。
那x和y怎么确定呢,3越多越大还是2越多越大,还是说3和2的搭配有种奇妙的关系呢?

结论如下:

当 n>5 时,我们尽可能多地剪长度为 3 的绳子;当剩下的绳子长度为 4 时,把绳子剪成两段长度为 2 的绳子。

因此就有了第二种解法。

2 贪婪

public int cutRope(int target) {
        if(target < 4)
            return target-1;
        int timesOf3 = target/3;
        if(target - 3*timesOf3 == 1)
            timesOf3 -= 1;
        int timesOf2 = (target - 3*timesOf3)/2;
        return (int)Math.pow(3,timesOf3)*(int)Math.pow(2,timesOf2);
    }  
全部评论

相关推荐

码农索隆:有点耳熟,你们是我教过最差的一届
点赞 评论 收藏
分享
一表renzha:不是你说是南通我都没往那方面想,人家真是想表达那个意思吗?
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
07-09 11:15
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务