=====================================================
对于问题二,给定一个小于1亿的数字a,给定一个集合B,求a在B中所有可能的组合。
Step1:将B中元素按照从小到大的次序依次排列,并表达为B={b[1](c[1]), b[2](c[2], ..., b[n](c[n])},这里的b[i]为每一个不同的元素值,而(c[i])则是b[i]值重复出现的次数。
简写为B={b[i](c[i])|b[i]<b[i+1], i=1,2,...,n}
Step2:构建子函数calc(value, B, startIndex):TList,用以在B的一个子集合(即只计算B'={b[i](c[i])|i>=startIndex})中计算指定的值value并返回其所有的组合。其返回值是一个列表,该列表中的每一个元素都是一颗树的根节点。内容的伪代码表示为:
var
singleSolution: TTreeNode;
laterSolutions: TList;
for i:=0 to c[startIndex] do
begin
lastValue:=value-b[startIndex]*i;
singleSolution := TTreeNode.create;
singleSolution.value := (b[startIndex], i);
if lastValue=0 then
result.add(singleSolution)
else
begin
laterSolutions:= calc(lastValue, B, startIndex+1);
if lasterSolution.count>0 then
begin
singleSolution.addChildrenNodes(laterSolutions);
result.add(singleSolution);
end ;
end ;
end ;
返回result;
Step3:在主程序中,调用solutions:= calc(a, B, 1),
if solutions.count>0 then
begin
依次遍历每一个solutions[i]树的所有路径,并输出。
end ;