這里使用VBScript做一個示范吧:
Dim ax, ex
ax=10^10
ex=""
Function Rec (Str1, InsertAt, Plus_N)
'注釋:Str1:當前字符串。InsertAt:當前指針的位置。Plus_N:剩余的加號數量
Dim a, StrA, StrB, StrC
If InsertAt = Len(Str1) Then '如果搜索到了字符串的末尾
If Plus_N = 0 Then '如果剩余加號數量為0,(而不是負數或正數)
a = Eval(Str1) '計算結果值 if a<ax Then '如果小于“最優值” ax = a '儲存他
ex = Str1
End If
Else
Exit Function
End If
Else
StrA = Mid (Str1, 1, InsertAt)'把字符串分段
StrB = Mid (Str1, InsertAt + 1, Len(Str1) - InsertAt)
Rec StrA & "+" & StrB, InsertAt + 2, Plus_N - 1 '先嘗試在其中插入加號的情況
Rec StrA & StrB, InsertAt + 1, Plus_N '再嘗試不插入加號的情況。這樣就能遍歷所有的情況了。
End If
End Function