Note: Standard combination generation:

1. Do not return when find diff < 0. Because i + 1 could satisfy.

2. Since it does not return, it requires check whether it reaches end of needs.

class Solution {
    public int shoppingOffers(List<Integer> price, List<List<Integer>> special, List<Integer> needs) {
        return generateComb(price, special, needs, new HashMap<>());
    }
    
    private int generateComb(List<Integer> price, List<List<Integer>> special, List<Integer> needs, Map<List<Integer>, Integer> map) {
        if (map.containsKey(needs)) return map.get(needs);
        int currentValue = getValue(price, needs);
        for (List<Integer> s : special) {
            List<Integer> clone = new ArrayList<>(needs);
            int i = 0;
            for (; i < clone.size(); i++) {
                int diff = clone.get(i) - s.get(i);
                if (diff < 0) break;
                clone.set(i, diff);
            }
            if (i == needs.size()) currentValue = Math.min(currentValue, s.get(s.size() - 1) + generateComb(price, special, clone, map));
        }
        map.put(needs, currentValue);
        return currentValue;
    }
        
        
    private int getValue(List<Integer> price, List<Integer> needs) {
        int result = 0;
        for (int i = 0; i < price.size(); i++) {
            result += price.get(i) * needs.get(i);
        }
        return result;
    }
}

 

posted on 2017-10-10 16:29  keepshuatishuati  阅读(104)  评论(0编辑  收藏  举报