注册一亩三分地论坛,查看更多干货!
您需要 登录 才可以下载或查看附件。没有帐号?注册账号
x
题目链接: 651. 4 Keys Keyboard
因为是付费题, 所以题目描述贴在这里:
Imagine you have a special keyboard with the following keys:
Key 1: (A): Prints one 'A' on screen.
Key 2: (Ctrl-A): Select the whole screen.
Key 3: (Ctrl-C): Copy selection to buffer.
Key 4: (Ctrl-V): Print buffer on screen appending it after what has already been printed.
Now, you can only press the keyboard for N times (with the above four keys), find out the maximum numbers of 'A' you can print on screen.
Example 1:
```
Input: N = 3
Output: 3
Explanation:
We can at most get 3 A's on screen by pressing following key sequence:
A, A, A
```
Example 2:
```
Input: N = 7
Output: 9
Explanation:
We can at most get 9 A's on screen by pressing following key sequence:
A, A, A, Ctrl A, Ctrl C, Ctrl V, Ctrl V
```
Note:
1. 1 <= N <= 50
2. Answers will be in the range of 32-bit signed integer.
Difficulty:Medium
Total Accepted:2.5K
Total Submissions:5.3K
Contributor: fallcreek
Companies
Microsoft Google
Related Topics
Math Greedy Dynamic Programming
Similar Questions
2 Keys Keyboard
这个题目标准的最优解是DP, 最简单的做法是N^2复杂度, 然后可以优化到N. 但是这种DP做法不是我问的. discussion有人发了一个帖子, 公布了一个O(1)时间和空间的math解法: https://discuss.leetcode.com/top ... rtest-and-fastest/3- int maxA(int N) {
- if (N <= 6) return N;
- if (N == 10) return 20;
- int n = N / 5 + 1, n3 = n * 5 - 1 - N;
- return pow(3, n3) * pow(4, n - n3);
- }
复制代码 这是原作者的解释:
> Pure math. This problem is to partition number N into 3's and 4's and get their product. n = N / 5 + 1is to compute the number of factors(the total number of 3's and 4's). With n, it's easy to know how many out of them are 3's by computing n3 = n * 5 - 1 - N. We minus 1 here because adding a single factor requires one step more than the factor itself, e.g. x4 takes 5 steps (select all, copy, paste, paste, paste). 10 is special here because it's the only > 6 number where there is no enough factors to share cuts from decrement of the number of 3's which means a 5 has to be introduced.
课时还是不太看得懂. 感觉是他的思路里面有什么重要的insight我没有捕捉到, 请教一下有没有大神能指点一二.
|