【剑指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。
输入描述:
输入一个数n,意义见题面。(2 <= n <= 60)
输出描述:
输出答案。
示例1
输入
8
输出
18

解题思路

  1. 答案提示是动态规划问题,应该先列公式再解
  2. 我用递归大法解决了,之所以有两个函数,是因为绳子至少被剪一刀,因此在cutRope中,target == i时就是没剪,不算,但是如果是一段被剪过的绳子,就可以不被再剪,因此target 等于i时成立,所以需要两个函数。

我的代码

public class Solution {
    public int cutRope(int target) {
        int res = 0;
        for(int i = 1; i < target; i++){
            int temp = i * cutRope1(target - i);;
            res = res > temp ? res : temp;
        }
        return res;
    }
    public int cutRope1(int target) {
        if(target == 0) return 1;
        int cut = 1, max = 0;
        while(cut <= target){
            int temp = cut * cutRope1(target - cut);
            ++cut;
            max = max < temp ? temp : max;
        }
        return max;
    }
}
发布了77 篇原创文章 · 获赞 1 · 访问量 5368

猜你喜欢

转载自blog.csdn.net/u010659877/article/details/104096391