650. 2 Keys Keyboard

来源:互联网 发布:seo sem是什么工作 编辑:程序博客网 时间:2024/06/01 09:16

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].

/*本答案为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[n];    }};
原创粉丝点击