我无法弄清楚如何使我的递归函数正常工作。我的想法是我有两套A和B,我需要打印A到B的所有归纳函数。这是我的递归函数,但是输出(下面列出的)不准确,我可以看到为什么问题存在我无法弄清楚如何解决它......
目前我有正确的A = {a,b,c}和B = {1,2,3,4}的输出数,即24,但它们包含重复数字的函数,这是不可接受的。一旦我通过它,我就失去了B [0]因此失去了例如......
的子集{2,1,3}任何指导都将不胜感激。
void nextFunction(vector<string> A,
vector<string> B,
vector<string> func,
int left,
mpq_class total,
int index) {
if (left == 0) {
print(func, A);
return;
}
for (int i = index; i < B.size(); ++i) {
func.push_back(B[i]);
nextFunction(A, B, func, left-1, total, index+1);
func.pop_back();
}
}
void print(vector<string> function, vector<string> A) {
for (int i = 0; i < (A.size()); ++i) {
cout << "(" << A[i] << "," << function[i] << ") ";
}
cout << endl;
}
输出:
(a,1)(b,2)(c,3)
(a,1)(b,2)(c,4)
(a,1)(b,3)(c,3)
(a,1)(b,3)(c,4)
(a,1)(b,4)(c,3)
(a,1)(b,4)(c,4)
(a,2)(b,2)(c,3)
(a,2)(b,2)(c,4)
(a,2)(b,3)(c,3)
(a,2)(b,3)(c,4)
(a,2)(b,4)(c,3)
(a,2)(b,4)(c,4)
(a,3)(b,2)(c,3)
(a,3)(b,2)(c,4)
(a,3)(b,3)(c,3)
(a,3)(b,3)(c,4)
(a,3)(b,4)(c,3)
(a,3)(b,4)(c,4)
(a,4)(b,2)(c,3)
(a,4)(b,2)(c,4)
(a,4)(b,3)(c,3)
(a,4)(b,3)(c,4)
(a,4)(b,4)(c,3)
(a,4)(b,4)(c,4)
答案 0 :(得分:0)
虽然我并不认为此问题是递归的理想选择,但您的算法可能如下所示:
PrintPossibleFunctions (range_values, already_chosen, fn_def):
if fn_def.size() == domain.size():
print elements in order, preceded by the corresponding domain element
return
for value in range_values:
if value not in already_chosen:
already_chosen.insert(value)
fn_def.push(value)
PrintPossibleFunctions(range_values, already_chosen, fn_def)
fn_def.pop()
already_chosen.remove(value)