# 1774. Closest Dessert Cost ###### tags: `Leetcode` `Bit Manipulation` `Medium` `Bit Mask` Link: https://leetcode.com/problems/closest-dessert-cost/ ## 思路 暴力枚举 由于每个topping最多用两个 所以用三进制表示每个topping用几个 ## Code ```java= class Solution { public int closestCost(int[] baseCosts, int[] toppingCosts, int target) { int n = baseCosts.length, m = toppingCosts.length; int minDiff = Integer.MAX_VALUE; int ans = Integer.MAX_VALUE; for(int i=0; i<n; i++){ int base = baseCosts[i]; for(int j=0; j<Math.pow(3, m); j++){ int mask = j; int top = 0; for(int k=0; k<m; k++){ top += toppingCosts[k]*(mask%3); mask/=3; } if(Math.abs(base+top-target)<minDiff){ minDiff = Math.abs(base+top-target); ans = base+top; } else if(Math.abs(base+top-target)==minDiff){ ans = Math.min(base+top, ans); } } } return ans; } } ```