650. 2 Keys Keyboard
2017-09-17 00:38
141 查看
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 exactly
n ‘A’ on the notepad by performing the minimum number of steps
permitted. Output the minimum number of steps to get n ‘A’.
Example 1: 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].
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 exactly
n ‘A’ on the notepad by performing the minimum number of steps
permitted. Output the minimum number of steps to get n ‘A’.
Example 1: 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上给出的参考答案*/ class Solution { public: int minSteps(int n) { if( n <= 1){ return 0; } for(int i = 2; i < n; i++){ if(n%i == 0){ return i + minSteps(n/i); } } return n; } };
class Solution { public: bool isPrime( int num ) { //两个较小数另外处理 if(num ==2|| num==3 ) return true ; //不在6的倍数两侧的一定不是质数 if(num %6!= 1&&num %6!= 5) return false ; int tmp =sqrt( num); //在6的倍数两侧的也可能不是质数 for(int i= 5;i <=tmp; i+=6 ) if(num %i== 0||num %(i+ 2)==0 ) return false ; //排除所有,剩余的是质数 return true ; } int minSteps(int n) { vector<int> dp(n+1,n); if(n < 0){ return 0; } dp[1] = 0; for(int i = 2;i <= n; i++ ){ dp[i] = i; if(!isPrime(i)){ for(int j = 1; j < i; j++){ int val = i%j; if(val == 0){ dp[i] = min(dp[j] + i/j,dp[i]); } } } } return dp ; } };
相关文章推荐
- LeetCode650. 2 Keys Keyboard
- LeetCode | 650. 2 Keys Keyboard 数学原理题分析
- Leetcode 650. 2 Keys Keyboard 2指键盘 解题报告
- 650. 2 Keys Keyboard
- LeetCode 650. 2 Keys Keyboard--动态规划
- Leetcode 650. 2 Keys Keyboard
- 【精】leetcode - 650. 2 Keys Keyboard 【动态规划 + 质数 & 非质数 + 简洁表达】
- [LeetCode] 650. 2 Keys Keyboard
- 650. 2 Keys Keyboard
- [Leetcode] 650. 2 Keys Keyboard 解题报告
- Leetcode 650. 2 Keys Keyboard
- leetcode 650. 2 Keys Keyboard(dp)
- 动态规划-650. 2 Keys Keyboard
- leetcode 650. 2 Keys Keyboard 最小复制粘贴次数 + 深度优先遍历DFS
- 650. 2 Keys Keyboard【Medium】可能是数学题
- [LeetCode] 650. 2 Keys Keyboard 两键的键盘
- leetcode 650. 2 Keys Keyboard
- [LeetCode] 650. 2 Keys Keyboard
- LeetCode 650. 2 Keys Keyboard
- LeetCode650. 2 Keys Keyboard