LeetCode650. 2 Keys Keyboard

来源:互联网 发布:网球王子u17漫画软件 编辑:程序博客网 时间:2024/05/29 16:38

原题:https://leetcode.com/problems/2-keys-keyboard/discuss/


题目:
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: 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:
The n will be in the range [1, 1000].


题解:
题中给出了两种操作:
1.复制当前的字符串;
2.将复制的字符串添加到原字符串后。
可以采用递归的方法。当目标字符串长度和当前字符串长度相等时,不需要任何操作,返回0,作为递归的终止条件。

当 n%2 = 0时, minStep(n) = minStep(n/2) + 2;
当 n%3 = 0时, minStep(n) = minStep(n/3) + 3;
当 n%5 = 0时, minStep(n) = minStep(n/5) + 5;
…….

事实上当n%k = 0且k为质数时, 想要从k变换到n,必须需要k步,即copy n/k,并paste k-1次。
而当n%k = 0且k为不为质数时时,假设k可以分解为m * n ;
如果将n直接分成k份,则需要m * n+minStep(n/k)步;
如果每次都除以较小因数因式分解,则需要m+n+minStep(n/k)步。
所以选择步数较少的第二种情况。


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;    }};

126 / 126 test cases passed.
Status: Accepted
Runtime: 3 ms