Minimum Number of Days to Eat N Oranges

There are n oranges in the kitchen and you decided to eat some of these oranges every day as follows:

  • Eat one orange.
  • If the number of remaining oranges (n) is divisible by 2 then you can eat  n/2 oranges.
  • If the number of remaining oranges (n) is divisible by 3 then you can eat  2*(n/3) oranges.

You can only choose one of the actions per day.

Return the minimum number of days to eat n oranges.

Example 1:

Input: n = 10
Output: 4
Explanation: You have 10 oranges.
Day 1: Eat 1 orange,  10 - 1 = 9.  
Day 2: Eat 6 oranges, 9 - 2*(9/3) = 9 - 6 = 3. (Since 9 is divisible by 3)
Day 3: Eat 2 oranges, 3 - 2*(3/3) = 3 - 2 = 1. 
Day 4: Eat the last orange  1 - 1  = 0.
You need at least 4 days to eat the 10 oranges.

思路:就是一个BFS + Set去重。

class Solution {
    public int minDays(int start) {
        Queue queue = new LinkedList();
        queue.offer(start);
        
        int step = 0;
        HashSet set = new HashSet();
        while(!queue.isEmpty()) {
            int size = queue.size();
            for(int i = 0; i < size; i++) {
                Integer n = queue.poll();
                if(n == 0) {
                    return step;
                }
                if(!set.contains(n - 1)) {
                    queue.offer(n - 1);
                    set.add(n - 1);
                }
                if(n % 2 == 0) {
                    if(!set.contains(n - n / 2)) {
                        queue.offer(n - n / 2);
                        set.add(n - n / 2);
                    }
                }
                if(n % 3 == 0) {
                    if(!set.contains(n - 2 *(n / 3))) {
                        queue.offer(n - 2 *(n / 3));
                        set.add(n - 2*(n / 3));
                    }
                }
            }
            step++;
        }
        return step;
    }
}

这题可以用DFS做, 还有个拐点就是:n %2 != 0  n % 3 != 0,那么代表n % 2, n % 3那些点是我们需要一个个吃的;

So, the real choice we have is to eat n % 2 oranges one-by-one and then swallow n / 2, or eat n % 3 oranges so that we can gobble 2 * n / 3.

class Solution {
    public int minDays(int n) {
        HashMap hashmap = new HashMap<>();
        return dfs(n, hashmap);
    }
    
    private int dfs(int n, HashMap hashmap) {
        if(hashmap.containsKey(n)) {
            return hashmap.get(n);
        }
        if(n == 0) {
            hashmap.put(0, 0);
            return 0;
        }
        if(n == 1) {
            hashmap.put(1, 1);
            return n;
        }
        hashmap.put(n, Math.min(dfs(n / 2, hashmap) + n % 2 + 1,dfs(n / 3, hashmap) + n % 3 + 1));
        return hashmap.get(n);
    }
}

 

你可能感兴趣的:(记忆化搜索,BFS)