LeetCode

来源:互联网 发布:知乎 多功能料理机 编辑:程序博客网 时间:2024/06/05 22:46

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

初始有一个A,现在只有两种操作。操作1:赋值所有的A;操作2:进行粘贴。问最少操作几次得到确切的n个A

动态规划,dp[i] = min(dp[i], dp[j] + i / j),跟每个数的因子有关系。时间复杂度O(n^2),空间复杂度O(n)

class Solution {public:    int minSteps(int n) {        vector<int> dp(n+1);        dp[0] = 0;        dp[1] = 0;        for (int i = 2; i <= n; ++i) {            dp[i] = i;            for (int j = i - 1; j >= 2; --j) {                if (i % j) continue;                dp[i] = min(dp[i], dp[j] + i / j);                break;            }        }        return dp[n];    }};

原创粉丝点击