2 Keys Keyboard_Week13

2 Keys Keyboard_Week13

题目:(2 Keys Keyboard) ←链接戳这里

题目说明:
Initially on a notepad only one character ‘A’ is present. You can perform two operations on this notepad for each step:

Copy All: You can copy all the characters present on the notepad (partial copy is not allowed).
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’.

难度: Medium

解题思路:
这道题刚看上去的时候很难,想了想觉得很简单,真的去做的时候又觉得有点难(…?).
一开始的思路是这样的,分成奇偶数,若是偶数,肯定可以对半分,找到2^n次方就可以,那奇数就可以是2^n+1的方式。
但是真正实践的时候发现这样是不对的,偶数算简单所以这样思考大概是没错的,但奇数的+1是无法实现的,因为只能复制全部,粘贴全部,那其实在已经有2^n的情况下是复制粘贴不了单独的一个字符的。

所以换一个类似分治的想法,将n分解,如果能被2整除,先分成2份,能被3整除,就分成三份,…,从i=2试分解到i=n,当没有别的因数的时候,(比如i=5)则说明这个数是没办法分解为小问题的,所以次数就等于5,即把一个字符复制一遍,粘贴4遍

为了简单好理解,所以使用了迭代的方法来实现,代码如下:

#include <iostream>
using namespace std;

class Solution {
public:
    int minSteps(int n) {
        if (n == 1) {//当只有一个数字时,不用复制粘体,所以操作为0 
            return 0;
        }
        for (int i = 2; i < n; i++) {
            if (n % i == 0) {//数字能被i整除,说明能由某个字符串(假设*)整体复制后,粘贴i次完成 
                //将问题拆分为小问题, 继续分析*字符串可以如何拆分,直到拆到n=1为止 
                // 次数加i 的意义为:复制1次,粘贴i-1次,所以次数+i 
                return i + minSteps(n/i); 
            }
        } 
    } 
};

猜你喜欢

转载自blog.csdn.net/m0_38072045/article/details/78700468
今日推荐