650. 2 Keys Keyboard

来源:互联网 发布:软件工作室英文缩写 编辑:程序博客网 时间:2024/06/05 19:37

Initially on a notepad only one character 'A' is present. You can perform two operations on this notepad for each step:

  1. Copy All: You can copy all the characters present on the notepad (partial copy is not allowed).
  2. 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: 3Output: 3Explanation: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:

  1. The n will be in the range [1, 1000].
解题思路,将一个数化为多个质数相乘得的形式即可,
比如20 = 4*5 =2*2*5,先copy(+1)和paste(+1) AA, 再copyall(+1) 和paste4次(+1),再copyall(+1) 和paste4次(+4)共九次,
先copy到5A,再copyall结果也是一样的,18= 2*3*3,和18=2*3*3的结果是一样的。
这样首先判断是不是质数,不是质数就进入一个递归处理,直到结束。

class Solution {public:    int minSteps(int n) {        if(n==1)            return 0;        for(int i = 2; i<=sqrt(n) ; i++){            if(n%i == 0)                return i+minSteps(n/i);        }        return n;    }};

二、不用递归,
在循环体中加一个while循环,用来进行相同数的因式分解(16=2*2*2*2),再循环遍历出所有的因子。整体思路不变。

class Solution {public:    int minSteps(int n) {        int res = 0;        for(int i=2; i<=n; i++){            while(n % i == 0){                res += i;                n /= i;            }        }        return res;    }};

三,使用动态规划
虽然是用动态规划不是很明智,但还是讲一下,如果我们计算出3和5的值时那么,3*5的值也就知道了,反过来我们要计算15的值可以通过3和5的值相加即可。若 i 能被 j 整除,则 i 的值 dp[i] = j 的值 dp[j] + (i/j)的值dp[i/j];这样一直循环下去就好了。
不过这个不适合动态规划,前两种是比较简单的做法。
class Solution {public:    int minSteps(int n) {        vector<int> dp(n+1, 0);        for(int i=2; i<=n; i++){            dp[i] = i;            for(int j=i-1; j>1;j--){                if(i%j == 0){                    dp[i] = dp[j] + (i/j);                    break;                }            }        }        return dp[n];    }};



原创粉丝点击