Leetcode 1774. Closest Dessert Cost 枚举法 vector 中的insert方法

  • vec中每个元素最多选两个
    • vec拼接成两段,进行枚举,这样就达到目的了
  • 枚举题
class Solution {
public:
    int closestCost(vector<int>& baseCosts, vector<int>& toppingCosts, int target) {
        int ans = INT_MAX;
        for (int i = 0; i < baseCosts.size(); i++) {
            int s;
            vector<int> vec = toppingCosts;
            vec.insert(vec.end(), toppingCosts.begin(), toppingCosts.end()); // vector 拼接
            for (int j = 0; j < 1 << vec.size(); j++) {
                int tmp = j;
                int record = vec.size() - 1;
                int cnt = 0;
                s=baseCosts[i];
                while (tmp) {
                    if (tmp & 1) {
                        s += vec[record];
                        cnt++;
                    }
                    tmp = tmp >> 1;
                    record--;
                }
                if (abs(s - target) < abs(ans - target)) ans = s;
                else if(abs(s - target) == abs(ans - target)) ans = min(s, ans);
            }
        }
        return ans;
    }
};
已标记关键词 清除标记
相关推荐
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页