我通过样本告诉我的意见...... 如果我们输入像{a,b,c,d}这样的序列,如果我们选择每个子序列3的元素数,它应该输出... a,b,c | a,b,d | a,c,d | b,c,d ....注意这个安排很重要(我正在使用数组)它的某种输出整个子集包含一个序列的3个元素....
#include <iostream>
#include <conio.h>
#include <windows.h>
int p = 0, q = 0, i;
void allinone(int thing[], int n, int sub, int tek[], int sum[])
{
for (i = p;i <= n - sub + p;i++)
{
tek[q] = thing[i];
if (p < sub - 1)
{
++q;
++p;
allinone(thing, n, sub, tek, sum);
}
if (q == (sub - 1))
{
for (auto out_p = 0;out_p <= p;out_p++)
std::cout << tek[out_p] << "\t";
std::cout << "\n";
}
}
--q;
return; // not need
}
int main()
{
constexpr int n=5, sub=3; //delete the constexpr if ur compiler is mingw
/*std::cout << "enter array len : "; //add this if ur compiler is mingw
std::cin >> n; // number of elements in sequence
std::cout << "enter sub that u want: ";
std::cin >> sub;*/ // subset
int sum[sub], tek[sub], thing[n];
for (i = 0;i <= n - 1;i++)
std::cin >> thing[i];
allinone(thing, n, sub, tek, sum);
_getch();
return 0;
}
哪个部分使程序不能回到上一个功能......
见下面的步骤......
我认为我认为承诺的问题是
#allinone1
first for pormise me it will do this for the i=0,1
{
doing for i=1{
sequence{a,b,c,d} thing[0]=a,thing[1]=b,thing[2]=c,thing[3]=d
tek[0] = a ... go into if ... p=1 , q=1 ... and again its going into the #allinone2 ...
now in the for its promise me to do this for i=1,2
{
doing for i=1
tek[1]= b ... go into if ... p=2 ,q=2 ... and again its going to #allinone3
another for its promise me to do this with i=2,3
{
doing for i=2
tek[2]= c .. go into the output if ... output a b c
doing for i=3
tek[2]= d .. go into output if ... output a d d
}get out of for
q=1
end of the allinone3
go into allinone 2 for
q is not 2 ...
doing for i=2 // i think this part made the problem ....
and ...
我认为它不存储最后一个......
答案 0 :(得分:0)
我看到的主要问题是您正在i
以及main
修改全局变量allinone
。
当你处理递归函数时,最好将用于终止递归的变量值作为参数传递给函数。
我稍微更新了你的代码,使递归更进一步。但是,它一直都不完美。它产生如下输出:
2 3 3
我会告诉你最后一点。
#include <iostream>
// Don't use global variables for variables that are used
// to terminate recursion.
// int p = 0, q = 0, i;
void allinone(int thing[], int n, int p, int sub, int tek[], int sum[])
{
int q = p;
for (int i = p; i <= n - sub + p; i++)
{
tek[q] = thing[i];
if (p < sub - 1)
{
allinone(thing, n, p+1, sub, tek, sum);
}
if (q == (sub - 1))
{
for (auto out_p = 0;out_p <= p;out_p++)
std::cout << tek[out_p] << "\t";
std::cout << "\n";
}
}
}
int main()
{
constexpr int n=5, sub=3; //delete the constexpr if ur compiler is mingw
/*std::cout << "enter array len : "; //add this if ur compiler is mingw
std::cin >> n; // number of elements in sequence
std::cout << "enter sub that u want: ";
std::cin >> sub;*/ // subset
int sum[sub], tek[sub], thing[n];
for (int i = 0;i <= n - 1;i++)
std::cin >> thing[i];
allinone(thing, n, 0, sub, tek, sum);
return 0;
}