2018-09-20 650. 2 Keys Keyboard

题意:给你初始一个A,再给你一串A,每次可以选择两种操作:复制当前所有字符,粘贴之前复制的字符。问你从一个给到指定个数的A最短需要多少步骤。
解题思路:本质就是求一个数的因子和。
假设最终串S有n个A,C代表拷贝,P代表粘贴,且最终串 = CPPCPCPPP,那么拆分一下操作步骤其实就是(CPP)(CP)(CPPP),在执行最后一个括号串操作之前,串的情况是S1 = (CPP)(CP),就是说S是S1的4倍,那么从S1到S需要操作4次,且4是n的一个因子。再往前S2 = CPP,就是说S1是S2的2倍,从S2到S1 需要操作2次,2同样是n的一个因子,依次类推,最少的操作步骤,其实就是n的所有因子和。
官方解释:
Intuition:We can break our moves into groups of (copy, paste, …, paste). Let C denote copying and P denote pasting. Then for example, in the sequence of moves CPPCPPPPCP, the groups would be [CPP][CPPPP][CP].

Say these groups have lengths g_1, g_2, …. After parsing the first group, there are g_1 ‘A’s. After parsing the second group, there are g_1 * g_2 ‘A’s, and so on. At the end, there are g_1 * g_2 * … * g_n ‘A’s.

We want exactly N = g_1 * g_2 * … * g_n. If any of the g_i are composite, say g_i = p * q, then we can split this group into two groups (the first of which has one copy followed by p-1 pastes, while the second group having one copy and q-1 pastes).

Such a split never uses more moves: we use p+q moves when splitting, and pq moves previously. As p+q <= pq is equivalent to 1 <= (p-1)(q-1), which is true as long as p >= 2 and q >= 2.

Algorithm: By the above argument, we can suppose g_1, g_2, … is the prime factorization of N, and the answer is therefore the sum of these prime factors.

class Solution {
public:
    int minSteps(int n) {
        int ans = 0, d = 2;
        while(n > 1){
            while(n % d == 0){
                ans += d;
                n /= d;
            }
            d++;
        }
        return ans;
    }
};

时间复杂度:O(n).

    原文作者:alexssssu
    原文地址: https://www.jianshu.com/p/f5e86edb74e8
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞