zoukankan      html  css  js  c++  java
  • 剑指Offer-67.剪绳子(C++/Java)

    题目:

    给你一根长度为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。

    分析:

    首先注意条件,剪成m段是要求大于1的,所以当绳子长2时,要返回1*1,为3时要返回1*2.

    其次我们不难发现,实际上减绳子就是要剪成长度为2或者3,且要让3的数量最多,例如6要剪成3*3,8要剪成2*3*3,

    所以我们可以先求出最多能减几份3,再根据剩余的绳子长度来求得最终解。

    当剩余绳子长度为0时,很明显返回3^3的个数,

    当剩余绳子长度为1时,此时我们应该拿出一段长度为3的绳子,和1拼成4,分成2*2,因为4>3,所以返回3^(3的个数-1)+ 2*2,

    当剩余绳子长度为2时,返回3^3的个数*2即可。

    程序:

    C++

    class Solution {
    public:
        int cutRope(int number) {
            if(number == 2)
                return 1*1;
            if(number == 3)
                return 1*2;
            int res = 0;
            int x = number / 3;
            int y = number % 3;
            if(y == 0){
                res += pow(3, x);
            }
            else if(y == 1){
                res += pow(3, x-1) * 2 * 2;
            }
            else{
                res += pow(3, x) * 2;
            }
            return res;
        }
    };

    Java

    public class Solution {
        public int cutRope(int target) {
            if(target == 2)
                return 1*1;
            if(target == 3)
                return 1*2;
            int res = 0;
            int x = target / 3;
            int y = target % 3;
            if(y == 0){
                res += Math.pow(3, x);
            }else if(y == 1){
                res += Math.pow(3, x-1) * 2 * 2;
            }else{
                res += Math.pow(3, x) * 2;
            }
            return res;
        }
    }
  • 相关阅读:
    安卓7.0手机拍照闪退问题解决
    自定义字体TextView
    Android Studio中的CmakeList NDK配置
    动态规划之最长公共子序列(LCS)
    快速排序
    KMP算法实现
    数据结构中的栈
    双向链式线性表(模板实现)
    Android Studio配置OpenCV(非NDK)
    AndroidStudio 1.4配置NDK
  • 原文地址:https://www.cnblogs.com/silentteller/p/12124872.html
Copyright © 2011-2022 走看看