且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在数组中查找总计为s的元素

更新时间:2022-11-13 22:38:27

这是一个著名的回溯问题,可以通过递归来解决。基本上是一种蛮力方法,其中尝试了所有可能的组合,但至少给出了3个边界条件,以简化搜索。

这是算法:

s变量,表示所选元素的总和,直到现在。

r变量表示剩余数组的总和。

M是所需的总和。

k是从0
$ b $开始的索引bw是给定整数的数组

It is a famous backtracking problem which can be solved by recursion. Basically its a brute force approach in which every possible combination is tried but 3 boundary conditions given at least prune the search.
Here is algorithm:
s variable for the sum of elements selected till now.
r variable for the overall sum of the remaining array.
M is the sum required.
k is index starting with 0
w is array of given integers

Sum(k,s,r)
{
    x[k]:=1;  //select the current element
    if(s<=M & r>=M-s & w[k]<=M-s)
    then
    {
        if(s+w[k]==M)
        then output all i [1..k] that x[i]=1
        else
        sum(k+1,s+w[k],r-w[k])
    }
    x[k]:=0  //don't select the current element
    if(s<=M) & (r>=M-s) & (w[k]<=M-s)
    then
    {
        if (M==s)
        then output all i [1..k] that x[i]=1
        else
        sum(k+1,s,r-w[k])
    }
}

我正在使用数组 x标记为解决方案选择的候选编号。在每个步骤3中,检查边界条件:

I am using an array "x" to mark the candidate numbers selected for solution. At each step 3 boundary conditions are checked:

1. Sum of selected elements in "x" from "w" shouldn't exceed M. s<M.    
2. Remaining numbers in array should be able to complete M. r>=M-s.
3. Single remaining value in w shouldn't overflow M. w[k]<=M-s.  

如果任何条件失败,则终止该分支。

If any of the condition is failed, that branch is terminated.