【CODE】2 Keys Keyboard

650. 2 Keys Keyboard

Medium

77954FavoriteShare

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].
class Solution {
public:
    bool isPrime(int n){
        int i=2;
        for(i=2;i<=sqrt(n);i++){
            if(n%i==0) return false;
        }
        return true;
    }
    int minSteps(int n) {
        if(n==1) return 0;
        if(isPrime(n)) return n;
        int flag=1;
        for(int i=1;i<=sqrt(n);i++){
            if(n%i==0) flag=i;
        }
        return minSteps(flag)+minSteps(n/flag);
    }
};
  • 上述用到思想:相同积,差值越小,和越小。
  • Runtime: 4 ms, faster than 76.29% of C++ online submissions for 2 Keys Keyboard.
  • Memory Usage: 8.2 MB, less than 75.00% of C++ online submissions for 2 Keys Keyboard.
  • Next challenges:
  • 4 Keys Keyboard
  • Broken Calculator
  • 以下递归,最少的复制粘贴次数:以18为例,18=1*18=2*9=3*6,因此有三种复制粘贴方法:(1)18次复制粘贴1个A / 1次复制粘贴18个A (2)9次复制粘贴2个A / 2次复制粘贴9个A (3)6次复制粘贴3个A / 3次复制粘贴6个A,分别需要的总次数是(1)18次  (2)复制粘贴到2个A的次数+9 / 复制粘贴到9个A的次数+2 (3)复制粘贴到3个A的次数+6 / 复制粘贴到6个A的次数+3
class Solution {
public:
    int minSteps(int n) {
        if(n==1) return 0;
        int res=n;
        for(int i=2;i<n;i++){
            if(n%i==0) res=min(res,minSteps(i)+n/i);
        }
        return res;
    }
};
发布了133 篇原创文章 · 获赞 35 · 访问量 6万+

猜你喜欢

转载自blog.csdn.net/Li_Jiaqian/article/details/102992596