LeetCode 2162. 设置时间的最少代价(枚举)
文章目錄
- 1. 題目
- 2. 解題
1. 題目
常見的微波爐可以設置加熱時間,且加熱時間滿足以下條件:
- 至少為 1 秒鐘。
- 至多為 99 分 99 秒。
你可以 最多 輸入 4 個數字 來設置加熱時間。
如果你輸入的位數不足 4 位,微波爐會自動加 前綴 0 來補足 4 位。
微波爐會將設置好的四位數中,前 兩位當作分鐘數,后 兩位當作秒數。
它們所表示的總時間就是加熱時間。比方說:
- 你輸入 9 5 4 (三個數字),被自動補足為 0954 ,并表示 9 分 54 秒。
- 你輸入 0 0 0 8 (四個數字),表示 0 分 8 秒。
- 你輸入 8 0 9 0 ,表示 80 分 90 秒。
- 你輸入 8 1 3 0 ,表示 81 分 30 秒。
給你整數 startAt ,moveCost ,pushCost 和 targetSeconds 。
一開始,你的手指在數字 startAt 處。
將手指移到 任何其他數字 ,需要花費 moveCost 的單位代價。
每 輸入你手指所在位置的數字一次,需要花費 pushCost 的單位代價。
要設置 targetSeconds 秒的加熱時間,可能會有多種設置方法。
你想要知道這些方法中,總代價最小為多少。
請你能返回設置 targetSeconds 秒鐘加熱時間需要花費的最少代價。
請記住,雖然微波爐的秒數最多可以設置到 99 秒,但一分鐘等于 60 秒。
示例 1:
示例 2:
輸入:startAt = 0, moveCost = 1, pushCost = 2, targetSeconds = 76 輸出:6 解釋:最優方案為輸入兩個數字 7 6,表示 76 秒。 手指移到 7 處(代價為 1),輸入 7 (代價為 2), 移到 6 處(代價為 1),輸入 6(代價為 2)。 總代價為:1 + 2 + 1 + 2 = 6 其他可行方案為 0076 ,076 ,0116 和 116 ,但是它們的代價都比 6 大。提示: 0 <= startAt <= 9 1 <= moveCost, pushCost <= 10^5 1 <= targetSeconds <= 6039來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/minimum-cost-to-set-cooking-time
著作權歸領扣網絡所有。商業轉載請聯系官方授權,非商業轉載請注明出處。
2. 解題
class Solution { public:int minCostSetTime(int startAt, int moveCost, int pushCost, int targetSeconds) {int m = targetSeconds/60, n = targetSeconds-m*60;vector<string> nums;if(m < 100) // 注意這個條件 <100to_str(m, n, nums);if(n+60 <= 99 && m>=1)to_str(m-1, n+60, nums);int mincost = INT_MAX;for(auto& s : nums){char start = char(startAt+'0');int cost = 0;for(auto c :s){if(c == start)cost += pushCost;else{cost += moveCost+pushCost;start = c;}}mincost = min(mincost, cost);}return mincost;}void to_str(int m, int n, vector<string>& nums){string a = m > 0 ? to_string(m) : ""; // 0不需要按string b = "00";if(n >= 10) b = to_string(n); // 兩位數else if(n > 0 && n <= 9 && m > 0) b = "0"+to_string(n);// 分鐘數不為0,秒鐘需要前置0else if(n > 0 && n <= 9 && m == 0) b = to_string(n);// 分鐘數為0,秒鐘不需要前置0nums.push_back(a+b);} };0 ms 6 MB C++
我的CSDN博客地址 https://michael.blog.csdn.net/
長按或掃碼關注我的公眾號(Michael阿明),一起加油、一起學習進步!
總結
以上是生活随笔為你收集整理的LeetCode 2162. 设置时间的最少代价(枚举)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python 全局变量、局部变量
- 下一篇: LeetCode 2125. 银行中的激