題意:給你初始一個A,再給你一串A,每次可以選擇兩種操作:復制當前所有字符,粘貼之前復制的字符。問你從一個給到指定個數(shù)的A最短需要多少步驟。
解題思路:本質就是求一個數(shù)的因子和。
假設最終串S有n個A,C代表拷貝,P代表粘貼,且最終串 = CPPCPCPPP,那么拆分一下操作步驟其實就是(CPP)(CP)(CPPP),在執(zhí)行最后一個括號串操作之前,串的情況是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).