劍指Offer-11-剪繩子

/**
 * 剪繩子-I  : https://leetcode-cn.com/problems/jian-sheng-zi-lcof/
 * 動態規劃
 * @Description
 */
public class Test12 {
    //動態規劃
    public int cuttingRope1(int n) {
        if (n < 2){
            return 0;
        }
        if (n == 2){
            return 1;
        }
        if (n == 3){
            return 2;
        }
        int[] products = new int[n + 1];
        products[0] = 0;
        products[1] = 1;
        products[2] = 2;
        products[3] = 3;
        int max = 0;
        for (int i = 4; i <= n ; i++) {
            max = 0;
            for (int j = 1; j <= i / 2 ; j++) {
                int product = products[j] * products[i-j];
                if (max < product){
                    max = product;
                }
                products[i] = max;
            }
        }
        return products[n];
    }
    //貪心算法
    public int cuttingRope(int n) {
        if (n < 2)return 0;
        if (n == 2)return 1;
        if (n == 3)return 2;
        int times3 = n / 3;
        if (n - times3 * 3 == 1){
            times3 -= 1;
        }
        int times2 = (n - times3*3) / 2;
        return (int)(Math.pow(3,times3)) * (int)(Math.pow(2,times2));
    }

    public static void main(String[] args) {
        System.out.println(new Test12().cuttingRope(50));
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章