将启发式应用于递归回溯

时间:2014-05-16 15:15:08

标签: c++ algorithm

搜索其他问题 - 并且有类似的问题,但没有一个处理这种特殊的启发式问题。

我有一个问题的工作代码,它要求将一个向量带入某个函数,确定该向量中的任何值是否总和到给定的目标值,然后返回它是否有(boolean)。这很简单。

我必须使用提供的回溯启发式来创建此功能(如下所示),原则上它正常工作。我必须确保我的函数不生成之前生成的组合(例如,ABC与BAC相同)。如何阻止我的代码执行此操作?我无法更改进入函数的参数(因此函数原型必须保持原样),但包装器或辅助函数都可以。

这是启发式:

  bool Solve(configuration conf) {
       if (no more choices) // BASE CASE
         return (conf is goal state);

  for (all available choices) {

        try one choice c;
        // recursively solve after making choice

  ok = Solve(conf with choice c made);
   if (ok) return true;
   else unmake choice c;

   }
   return false; // tried all choices, no soln found
  }

我的代码:

bool CanMakeSum(Vector<int> & nums, int targetSum) {

if (nums.isEmpty()) { 

    cout << "you've reached the target sum" << endl;
    return true;

} else {

    for (int i  = 0; i < nums.size(); i++) {

        element = nums[i];
        Vector<int> rest = nums;
        cout << "list the subset: " << listSubset(rest) << endl;
        rest.removeAt(i);

        // try one          
        int new_target_sum = targetSum - element;

        CanMakeSum(rest, new_target_sum);

            if (new_target_sum == 0) {
                return true;

            } else {

            new_target_sum = targetSum + element;

        }
    }
}

return false;
}


string listSubset(Vector<int> &partial_solution) {

string solution = " ";

for (int i = 0; i < partial_solution.size(); i++) {
    solution += IntegerToString(partial_solution[i]) + " ";
}

return solution;

}

1 个答案:

答案 0 :(得分:1)

您可以在选择元素时引入排序。例如,在选择ith元素后,您无法选择索引小于i的任何元素。代码中所需的更改是在选择第i个元素后,您需要删除索引0到i的所有元素。