zoukankan      html  css  js  c++  java
  • 剑指offer-面试题14-剪绳子-动态规划法

    /*
    题目:
    	给定一个长度为n的绳子,把绳子剪为m段,(n>1,m>1)
    	求各段绳子乘积的最大值。
    */
    /*
    思路:
    	动态规划。
    	f(n)=max(f(1)*f(n-1),f(2)*f(n-2),f(3)*f(n-3),...,f(n/2)*f(n-n/2))。
    	求最优解。
    	大问题可分解为若干个小问题。
    	大问题的解依赖小问题的解。
    	自顶向下分析问题,自底向上求解问题。
    */
    #include<iostream>
    #include<string.h>
    #include<algorithm>
    using namespace std;
    int cutRope(int number){
        if(number <= 1){
            throw("invalid parameter");
        }
        if(number == 2 || number == 3){
            return number-1;
        }
        int* maxProduct = new int[number+1];
        memset(maxProduct,0,number+1);
        maxProduct[1] = 1;
        maxProduct[2] = 2;
        maxProduct[3] = 3;
        int max = 0;
        for(int len = 4; len <= number; len++){
            max = 0;
            for(int left = 1; left <= len / 2; left++){
                cout<<len<<" "<<left<<" "<<len-left<<endl;
    
                int product =  maxProduct[left] * maxProduct[len-left];
                if(max < product){
                    max = product;
                }
            }
            maxProduct[len] = max;
            //cout<<maxProduct[len]<<endl;
        }
        max = maxProduct[number];
        delete[] maxProduct;
        return max;
    }
    
    
    int main(){
        cout<<cutRope(8)<<endl;
    }
    

       

  • 相关阅读:
    需求获取过程中的逆向沟通
    程序员==生 涯 篇
    算法设计
    灯的启示:微软对唐骏的面试题
    使用Gzip压缩提升WEB服务器性能
    简历误区
    招聘编辑的七道面试题
    web2.0及其相关技术
    经典面试题助你成功就业
    逗号网站推广营销策略
  • 原文地址:https://www.cnblogs.com/buaaZhhx/p/11845540.html
Copyright © 2011-2022 走看看