题干:
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: 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’.
题目解析:
这道题目可以使用贪心算法进行求解,要最少步数到达数目n,copy+paste是最好的选择,于是从2开始不断递增,使n不断减少,每减少一次就是copy+paste的次数,当最后减无可减时,若为1,则不用再加步骤,若大于1,则使用最朴素的一个A不断复制即可。
AC代码如下:
class Solution {
public:
int minSteps(int n) {
int ans = 0;
for (int i = 2; i <= n; i ++) {
while (n % i == 0) {
ans += i;
n /= i;
}
}
if (n > 1)
ans += n;
return ans;
}
};