题:
思:深搜暴力解法
码:
public static int shoppingOffers(List<Integer> price, List<List<Integer>> special, List<Integer> needs) {
// 深搜 要使得needs的所有元素恰好变为0时,所需的最小的价格和
// 对于needs的每一项,只要不为0,就有以下几种选择:
// 1.直接减少自己 2.寻找一个包含自己的礼包,对于每一种情况,分别 探讨是否可以购买本礼包,如果可以,则购买
// 如果needs这一项为0,则考虑下一项
// 递归结束条件,当递归到needs的最后一项时,递归结束,更新最小的价格和
int minSum[] = new int[1];
minSum[0] = Integer.MAX_VALUE;
dfs(price, special, needs, 0, minSum, 0);
return minSum[0];
}
public static void dfs(List<Integer> price, List<List<Integer>> special, List<Integer> needs, int curPriceSum, int[] minSum, int curIndex) {
// 递归结束条件
if (curIndex == needs.size()) {
minSum[0] = Math.min(curPriceSum, minSum[0]);
return;
}
if (needs.get(curIndex) > 0) {
// 单买,买完以后记得加回来
needs.set(curIndex, needs.get(curIndex) - 1);
dfs(price, special, needs, curPriceSum + price.get(curIndex), minSum, curIndex);
needs.set(curIndex, needs.get(curIndex) + 1);
// 通过大礼包购买,考虑所有大礼包的情况
for (int i = 0; i < special.size(); i++) {
List<Integer> libao = special.get(i);
int k = 0;
for (; k < libao.size() - 1; k++) {
if (libao.get(k) > needs.get(k)) {
break;
}
}
if (k < libao.size() - 1)
continue;
else {
// 可以买这个礼包
for (int l = 0; l < libao.size() - 1; l++) {
needs.set(l, needs.get(l) - libao.get(l));
}
dfs(price, special, needs, curPriceSum + libao.get(libao.size() - 1), minSum, curIndex);
for (int l = 0; l < libao.size() - 1; l++) {
needs.set(l, needs.get(l) + libao.get(l));
}
}
}
} else {
dfs(price, special, needs, curPriceSum, minSum, curIndex + 1);
}
}