要输入n个字符,求最少击键次数
int minSteps(int n) {
// 一组操作是C后带若干个P,CP、CPP、...,最终n=len(CP)*len(CPP)*...
// 这题就是把n因子分解,求所有>=2因子的和
int ans = 0, factor = 2;
while (n > 1) {
while (n % factor == 0) {
ans += factor;
n /= factor;
}
factor++;
}
return ans;
}
击键n次,最多能输入多少字符
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.
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, AExample 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 VNote:
- 1 <= N <= 50
- Answers will be in the range of 32-bit signed integer.
int maxA(int N) {
// dp[i]表示按i次键盘时A的最大个数
// 一种是按1次A,dp[i]=dp[i-1]+1
// 一种是成组按3<=k<=i次,ctrlA+ctrlC+(k-2)ctrlV,字符数 *= (k-1)
// dp[i]=max{ dp[i-k] * (k-1) }
vector<int> dp(N + 1, 0);
for (int i = 1; i <= N; i++) {
dp[i] = dp[i-1] + 1;
for (int k = 3; k <= i; k++) {
dp[i] = max(dp[i], dp[i-k] * (k-1));
}
}
return dp[N];
}