0
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;
    }
}

Can somebody explain why this is not working but the code below is working? The functions try to find if a target weight can be calculated with given weights on a balance scale. Both functions check 3 possibilites which are adding a weight to the left and continuing, adding a weight to the right and continuing or not using any weights and continuing.

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 Answers0