650. 2 Keys Keyboard

Problem:

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

思路

要得到n个'A'可以通过如下方式得到:

  1. 如果n为质数,那么只能通过复制一次加上粘贴n-1次得到,总共需要n次;
  2. 如果n为合数,那么可以通过对n进行质因数分解,得到n所有的质因数,因为质因数不能再分解,所以总共的次数为n的所有质因数之和。

Solution (C++):

int minSteps(int n) {
    if (n == 1)  return 0;
    if (isPrime(n))  return n;
    return factorization_sum(n);
}
bool isPrime(int n) {
    if (n == 2)  return true;
    for (int i = 2; i <= sqrt(n); ++i) {
        if (n % i == 0)  return false;
    }
    return true;
}
int factorization_sum(int n) {
    vector<int> fac;
    int sum = 0;
    while (n > 1) {
        for (int i = 2; i <= n; ++i) {
            if (n % i == 0) {
                fac.push_back(i);
                n /= i;
                break;
            }
        }
    }
    for (auto x : fac)  sum += x;
    return sum;
}

性能

Runtime: 0 ms  Memory Usage: 6 MB

思路

与上面的思路类似,但是简化了分解的过程:

  1. 如果n是质数,则总共的次数为n次;
  2. 如果n是合数,则n可以通过分解成2个数的乘积,然后等于分别得到这2个数的次数之和。

Solution (C++):

int minSteps(int n) {
    vector<int> dp(n+1, 0);

    for (int i = 2; i <= n; ++i) {
        if (isPrime(i))  dp[i] = i;
        else {
            for (int j = 2; j <= sqrt(n); ++j) {
                if (i % j == 0) {
                    dp[i] = dp[j] + dp[i/j];
                    break;
                }
            }                
        }
    }
    return dp[n];
}
bool isPrime(int n) {
    if (n == 2)  return true;
    for (int i = 2; i <= sqrt(n); ++i) {
        if (n % i == 0)  return false;
    }
    return true;
}

性能

Runtime: 4 ms  Memory Usage: 6.7 MB

原文链接: https://www.cnblogs.com/dysjtu1995/p/12724643.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍;

也有高质量的技术群,里面有嵌入式、搜广推等BAT大佬

    650. 2 Keys Keyboard

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/342944

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年3月2日 上午1:49
下一篇 2023年3月2日 上午1:50

相关推荐