动态规划中级教程。 650. 2 Keys Keyboard

Initially on a notepad only one character 'A' is present. You can perform two operations on this notepad for each step: 

  1. Copy All: You can copy all the characters present on the notepad (partial copy is not allowed).
  2. Paste: You can paste the characters which are copied last time.

Given a number n. You have to get exactly n 'A' on the notepad by performing the minimum number of steps permitted. Output the minimum number of steps to get n 'A'. 

Example 1:

Input: 3
Output: 3
Explanation:
Intitally, we have one character 'A'.
In step 1, we use Copy All operation.
In step 2, we use Paste operation to get 'AA'.
In step 3, we use Paste operation to get 'AAA'.

Note:

  1. The n will be in the range [1, 1000].

题目说给你一个初时的a

你只可以有两种操作

1.全选(不可以选部分)

2.复制

跟以前一样分析

dp【0】 = 0;

dp【1】 = 0;初时有1个

dp【2】 = 2;全选后复制

dp【3】 =3;全选-复制-复制

dp【4】= 4;可以全选复制-复制-复制也可以全选-复制-全选-复制但是如果方案1 我们就没有子问题 我们希望是方案二

。。。。。;来看一个大点的例子

dp【9】 =6(如果你不笨的话, 这里应该全选-复制-复制-全选-复制-复制  而前三步正好是dp【3】的步骤

接着我们分析

dp【11】=11;因为11是素数它没有共因子我们只能一路复制

看看

dp【121】=22;我们用dp【11】全选一次复制十次

这时我们得到的状态转移方程是

if( I %j ==0)

dp【i】=dp【j】+j;

else

dp【i】=i;

class Solution {
public:
    int minSteps(int n) {
        if(n<=0)return NULL;
        if(n==1)return 0;
        if(n==2)return 2;
        int dp[n+1];
        for(int i=0;i<=n;i++)
        {
            dp[i]=0;
        }
        dp[2]=2;
        for(int i=3;i<=n;i++)
        {
            bool cando=true;
            for(int j=2;j<i;j++)
            {
                if(i%j==0)
                {
                    dp[i]=dp[i/j]+j;
                    cando=true;
                    break;
                }
                else
                {
                    cando=false;
                }
            }
            if(!cando)
            {
                dp[i]=i;
            }
        }
        return dp[n];
    }
};



  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值