帮我解决这个递归组合算法
各位, 我有 N 个有界集合:
S1 = {s11, s12, ... s1a }
S2 = {s21, s22, ... s2b }
...
sN= {sN1, sN2, ... sNx }
我有一个函数 f(),它从每个集合中获取一个参数 A:
f( A1, A2, ... AN ) such that Ax belongs to Sx
我需要为所有可能的参数组合调用 f():
f( s11, s21, ... sN1 )
f( s11, s21, ... sN2 )
f( s11, s21, ... sN3 )
...
f( s11, s21, ... sNx )
...
f( s1a, s2b, ... sNx )
有人能帮我找出一种递归(或迭代)算法吗?会击中所有组合吗?
提前致谢。
-拉吉
Folks,
I have N bounded sets:
S1 = {s11, s12, ... s1a }
S2 = {s21, s22, ... s2b }
...
sN= {sN1, sN2, ... sNx }
I have a function f() that takes one argument A from each set:
f( A1, A2, ... AN ) such that Ax belongs to Sx
I need to invoke f() for all possible combinations of arguments:
f( s11, s21, ... sN1 )
f( s11, s21, ... sN2 )
f( s11, s21, ... sN3 )
...
f( s11, s21, ... sNx )
...
f( s1a, s2b, ... sNx )
Can someone help me figure out a recursive (or iterative) algorithm that will hit all combinations?
Thanks in advance.
-Raj
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
所以基本上你想生成 笛卡尔积
s1 x s2 x ... x sN
。这是回溯/递归的经典应用。伪代码如下所示:
您应该将其写在纸上并看看它是如何工作的。例如,考虑集合:
第一个调用将是
CartesianProduct({}, 1)
,然后它将开始迭代第一个集合中的元素。因此第一个递归调用是CartesianProduct({1}, 2)
。这将以同样的方式继续下去,最终达到CartesianProduct({1, 3, 5}, 4)
,其终止条件将为 true (current.Length == N + 1)。然后回溯并调用CartesianProduct({1, 3, 6}, 4)
等等,直到生成所有可能性。在纸上一路运行它,看看它到底是如何工作的。额外加分:你能弄清楚如何去掉
k
参数吗?So basically you want to generate the cartesian product
s1 x s2 x ... x sN
.This is a classic application of backtracking / recursion. Here's how a pseudocode would look like:
You should write it on paper and see how it works. For example, consider the sets:
The first call will be
CartesianProduct({}, 1)
, which will then start iterating over the elements in the first set. The first recursive call with thus beCartesianProduct({1}, 2)
. This will go on in the same manner, eventually reachingCartesianProduct({1, 3, 5}, 4)
, for which the termination condition will be true (current.Length == N + 1
). Then it will backtrack and callCartesianProduct({1, 3, 6}, 4)
and so on, until all possibilities are generated. Run it on paper all the way to see exactly how it works.A
Extra credit: can you figure out how to get rid of the
k
parameter?