您的位置:首页 > 其它

[LeetCode] 2 Keys Keyboard

2018-01-11 02:46 381 查看
题干:

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;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: