LeetCode 202nd weekly contest 1553. The minimum number of days to eat N oranges (simple memory search)

Insert picture description here

Ideas:

  • Simple DFS or BFS will definitely time out, just add a record set to pruning.
  • At the same time, using the characteristics of BFS layer sequence traversal, the first answer found is output.

Code:

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;
    }
};

Guess you like

Origin blog.csdn.net/qq_43663263/article/details/108069443