650. 2 Keys Keyboard

来源:互联网 发布:web前端开发 薪资知乎 编辑:程序博客网 时间:2024/06/06 00:54

题目

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].
分析

第一种方法可以模拟copy和paste操作,找到所有可能的操作个数,最后取最小值,这样的方法比较费时,另一种方法是根据n来决定操作个数,令f(n)表示构造长度为n所需的操作次数,如果n能被2整除,则f(n)=f(n/2)+2,即f(n/2)时copy并paste,类似n能被3整除时,f(n)=f(n/3)+3,则n能被i整除,f(n)=f(n/i)+i。

方法一:

class Solution {public:    void steps(int n,int curlen,int copy,int cnt,int& minStep){        if(curlen+copy==n){//如果当前长度+copy==n,则只需要一次paste即可,故minStep与cnt+1取最小            minStep=min(minStep,cnt+1);            return ;        }        else if(curlen+copy<n){//否则如果不到n,则有两种方案            steps(n,curlen+copy,copy,cnt+1,minStep);//第一是paste并且不copy,只增加一次操作            steps(n,curlen+copy,curlen+copy,cnt+2,minStep);//第二是paste并且copy,增加两次操作        }        return ;    }    int minSteps(int n) {        if(n==1){//如果n等于0,则无需复制粘贴直接返回            return 0;        }        int curlen=1;//当前长度初始化为1        int copy=1;//copy初始化为1        int minStep=INT_MAX;//保存最小的步骤个数        steps(n,curlen,copy,1,minStep);        return minStep;    }};
方法二:

class Solution {public:    int minSteps(int n) {        if (n == 1) return 0;        for (int i = 2; i < n; i++)            if (n % i == 0)                 return i + minSteps(n / i);        return n;    }};
参考文章:[C++] Clean Code with Explanation - 4 lines, No DP


原创粉丝点击