Initially on a notepad only one character 'A' is present. You can perform two operations on this notepad for each step:
Copy All
: You can copy all the characters present on the notepad (partial copy is not allowed).Paste
: You can paste the characters which are copied last time.Given a number
n
. You have to get exactlyn
'A' on the notepad by performing the minimum number of steps permitted. Output the minimum number of steps to getn
'A'.Example:
Input: 3 Output: 3 Explanation: Intitally, we have one character 'A'. In step 1, we use Copy All operation. In step 2, we use Paste operation to get 'AA'. In step 3, we use Paste operation to get 'AAA'.
Note:
- The
n
will be in the range [1, 1000].
概述
最近在LeetCode上刷dp题玩,遇到这个骗子题,居然标中等难度。
思路
题目大意:开始有1个A,每次可以复制当前数量的A任意(设为k)遍,该行动需要k个步骤,问得到n个A的最少步骤数。
首先观察,在一个可能的方案中,A的数量有下述变化:1 -> a0 -> a0*a1 -> a0*a1*a2 ->...-> n
该方案操作数为a0+a1+...+ak.
ai(0<=i<=k)都是n的因子。方案操作数实际上就是n的一个因子和。
直觉想到,如果n=a*b,其中a,b>1,那么n>=2*max(a,b)>=a+b.
于是n的因子和中,质因子和最小,求质因子和即可。
一个最大O(n)的简单数学题,dp预处理O(n^2)更适用大n配多输入场合。
代码
class Solution {
public:
int minSteps(int n) {
int r=0;
for(int i=2;i<=n;){
if(n%i==0){
r+=i;
n/=i;
}else i++;
}
return r;
}
};
http://www.cnblogs.com/hizcard/ 转载请注明出处