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

来源:互联网 发布:vimeo软件下载 编辑:程序博客网 时间:2024/06/11 20:12

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: 3Output: 3Explanation: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];    }};



原创粉丝点击