[leetcode]651. 4 Keys Keyboard

来源:互联网 发布:吸血女伯爵 知乎 编辑:程序博客网 时间:2024/06/10 02:06

dynamic programming

题目:

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 = 3Output: 3Explanation: We can at most get 3 A's on screen by pressing following key sequence:A, A, A

Example 2:

Input: N = 7Output: 9Explanation: 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 <= N <= 50
Answers will be in the range of 32-bit signed integer.

思路:

要想增加A的个数,要么直接输入A,要么至少需要3步来实现Ctrl A, Ctrl C, Ctrl V的操作,即第i-2步输入Ctrl A, 第i-1步输入Ctrl C, 第i步输入Ctrl V,当前A的个数=[i-3]*2。
使用动态规划,dp[i]表示步骤总数为i时,能够打印的A的最大值。要么一点不使用copy操作,就是我们初始化 DP[ i ] 为 i 的情形;要么使用copy操作,这样我们要留3步给 Ctrl A, Ctrl C, Ctrl V ,所以 j 至少是 3。
dp[j-1]*(i-j)):输入操作的步骤区间为[j, i], 共(i-j+1)个步骤,有M=(i-j+1)-2个操作输入Ctrl V,则dp[j-1]需要乘以M*2。

代码:

int maxA(int n) {    vector<int> dp(n+1);    int i;    for (i = 0; i < n+1; i++) {        dp[i] = i;//初始化dp,假设dp[i]是一直输入a的第i步时a的总数     }    for (i = 1; i < n+1; i++) {        for (int j = 3; j < i-2; j++) {            dp[i] = max(dp[i], dp[j-1]*(i-j));        }    }     return dp[n];}