problem:https://leetcode.com/problems/2-keys-keyboard/
重做此题,发现依然只能写出N2的算法,水平并没有提升TAT
class Solution { public: int minSteps(int n) { vector<vector<int>> dp(n + 1, vector<int>(n + 1, 10000)); if(n == 1) return 0; dp[1][1] = 1; for(int i = 2;i <= n;i++) { int minnum = INT_MAX; for(int j = 1; j < i; j++) // do parse { dp[i][j] = min(dp[i][j], dp[i - j][j] + 1); minnum = min(dp[i][j], minnum); } dp[i][i] = minnum + 1; // do copy } return *min_element(dp[n].begin(), dp[n].end()); } };
从评论区拿到的advance版本。这道题的标准解法是分解质因数。最优解的证明已经涉及到一些数学上的问题了。
class Solution { public: int minSteps(int n) { vector<int> dp(n + 1, INT_MAX); dp[1] = 0;
for (int i = 2; i <= n; i++) { dp[i] = i; for (int j = i/2; j > 1; j--) { if (i % j == 0) { dp[i] = dp[j] + (i / j); break; } } }
return dp[n]; } };