C ++:具有2个功能的权衡问题

时间:2020-08-15 14:25:33

标签: c++ recursion recursive-backtracking

bool isMeasurable(int target, std::vector<int>& weights, int current, unsigned int index){
    if(index<=weights.size()-1){
        if(target==current){
            return true;
        } else {
            return isMeasurable(target+weights[index], weights, current, index+1) ||
                    isMeasurable(target, weights, current+weights[index], index+1) ||
                        isMeasurable(target, weights, current, index+1);
        }
    } else {
        return false;
    }
}

有人可以解释为什么这不起作用但是下面的代码起作用吗?这些功能尝试查找是否可以在天平上使用给定的重量来计算目标重量。这两个功能都会检查3个可能的对象,这三个对象正在向左侧添加权重并继续,向右侧添加一个权重并继续使用或不使用任何权重并继续。

bool isMeasurable(int target, Vector<int>& weights) {
    if (weights.isEmpty()) {
        return target == 0; // base case; no weights left to place
    } else {
        int last = weights[weights.size() - 1]; //using last index is fastest
        weights.remove(weights.size() - 1);

        // "choose and explore" all of the three possibilities
        bool result = isMeasurable(target + last, weights) ||
               isMeasurable(target - last, weights) ||
               isMeasurable(target, weights);
        // un-choose
        weights.add(last);
        return result;
    }
}

0 个答案:

没有答案
相关问题