链接:http://www.lintcode.com/zh-cn/problem/4-keys-keyboard/
Imagine you have a special keyboard with the following keys:
Key 1
: (A): Print 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.
注意事项
1 <= N <= 50
- Answers will be in the range of 32-bit signed integer.
Given N = 3
, return 3
.
Explanation:
We can at most get 3 A's on screen by pressing following key sequence:
A, A, A
Given N = 7
, return 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
首先把 DP[ i ] 初始化为 i,代表的情形是不使用复制粘贴操作。然后将 j 从3开始一直到 i-1,从3开始是为了确保至少有一个复制粘贴的操作。接着循环:"以dp[1] 中的所有字符为基准之后全是粘贴操作" 一直到 "以dp[i-3]中的所有字符为基准之后全是粘贴操作"。
比如:
A, A, A, Ctrl A, Ctrl C, Ctrl V, Ctrl V
这里 n = 7
,我们使用了 3
(j=4,i-j=7-4)步来获得 AAA
接着我们使用 4
步: Ctrl A, Ctrl C, Ctrl V, Ctrl V, 来获得j
- 1 = 4 - 1 = 3
份 AAA 的复制。
我们要么一点不使用copy操作,就是我们初始化 DP[ i ] 为 i 的情形。要么使用copy操作,这样我们要留3步给 Ctrl A, Ctrl C, Ctrl V ,所以 j 至少是 3
.
class Solution {
public:
/**
* @param N: an integer
* @return: return an integer
*/
int maxA(int N) {
// write your code here
vector<int> dp(N+1,0);
for(int i=1;i<=N;i++)
{
dp[i]=i;
for(int j=3;j<i;j++)
{
dp[i]=max(dp[i],dp[i-j]*(j-1));
}
}
return dp[N];
}
};