Leetcode 650.只有两个键的键盘
Posted kexinxin
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Leetcode 650.只有两个键的键盘相关的知识,希望对你有一定的参考价值。
只有两个键的键盘
最初在一个记事本上只有一个字符 \'A\'。你每次可以对这个记事本进行两种操作:
- Copy All (复制全部) : 你可以复制这个记事本中的所有字符(部分的复制是不允许的)。
- Paste (粘贴) : 你可以粘贴你上一次复制的字符。
给定一个数字 n 。你需要使用最少的操作次数,在记事本中打印出恰好 n 个 \'A\'。输出能够打印出 n 个 \'A\' 的最少操作次数。
示例 1:
输入: 3
输出: 3
解释:
最初, 我们只有一个字符 \'A\'。
第 1 步, 我们使用 Copy All 操作。
第 2 步, 我们使用 Paste 操作来获得 \'AA\'。
第 3 步, 我们使用 Paste 操作来获得 \'AAA\'。
说明:
- n 的取值范围是 [1, 1000] 。
思路
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.
1 class Solution { 2 public int minSteps(int n) { 3 int ans = 0, d = 2; 4 while (n > 1) { 5 while (n % d == 0) { 6 ans += d; 7 n /= d; 8 } 9 d++; 10 } 11 return ans; 12 } 13 }
以上是关于Leetcode 650.只有两个键的键盘的主要内容,如果未能解决你的问题,请参考以下文章
leetcode 650. 2 Keys Keyboard 只有两个键的键盘(中等)
LeetCode 292. Nim 游戏(博弈) / 650. 只有两个键的键盘 / 673. 最长递增子序列的个数(LIS二分+前缀和) / 58. 最后一个单词的长度