LeetCode 第 202 场周赛 1553. 吃掉 N 个橘子的最少天数(简单记忆化搜索)

在这里插入图片描述

思路:

  • 朴素的DFS或者BFS肯定会超时的,只需要加上一个记录的set来剪枝即可。
  • 同时利用BFS层序遍历的特点,输出第一个找到的答案。

代码:

class Solution {
    
    
public:
    int minDays(int n) {
    
    
        int ans=0;
        unordered_set<int> temp;
        queue<int> q;
        q.push(n);
        temp.insert(n);
        while(!q.empty()){
    
    
            int n=q.size();
            for(int i=0;i<n;i++){
    
    
                int x=q.front();
                q.pop();
                if(x==0)
                return ans;
                if(x%3==0&&temp.count(x/3)==0)
                {
    
    
                    q.push(x/3);
                    temp.insert(x/3);
                }
                if(x%2==0&&temp.count(x/2)==0)
                {
    
    
                    q.push(x/2);
                    temp.insert(x/2);
                }
                if(temp.count(x-1)==0)
                {
    
    
                    q.push(x-1);
                    temp.insert(x-1);
                }
            }
            ans++;
        }
        return 0;
    }
};

猜你喜欢

转载自blog.csdn.net/qq_43663263/article/details/108069443