using namespace std;
static int a[8] = {0, 1, 2, 3, 4, 5, 6, 7};
static int c[5] = {-1, -1, -1, -1, -1};
void RecursionBase(int start, int pos, int surplusCount, int originArrayCount, int needCount);
void RecursionTest() {
RecursionBase(0, 0, 5, 8, 5);
}
/**
*
* @param start start mark
* @param pos choice mark
* @param surplusCount array processing need surplus array count
* @param originArrayCount origin array(length is max than need choice array)
* @param needCount need count
*/
void RecursionBase(int start, int pos, int surplusCount, int originArrayCount, int needCount) {
if (surplusCount == 0) { //代表数组剩余个数已经取完毕了,开始打印
for (int i = 0; i < needCount; i++) {
cout << c[i] << ",";
}
cout << endl;
return;
}
// 原始数组个数(大的数组里) - 剩余个数 +1 为最大允许遍历到的位置,防止角标越界
for (int i = pos; i < originArrayCount - surplusCount + 1; i++) {
//新数组角标从0开始一个个赋值,0负值结束,递归找c[1]开始赋值,直到把新数组找满。
//下一次在进入则替换尾巴的值,不断赋值(最内层递归)
c[start] = a[i];
//给c的下一个节点赋值,赋值的起始位置为当前循环 +1,当前循环的起始值为了保障不重复,传入的pos 必须扩大
RecursionBase(start + 1, i + 1, surplusCount - 1, originArrayCount, needCount);
}
}
执行结果。
0,1,2,3,4,
0,1,2,3,5,
0,1,2,3,6,
0,1,2,3,7,
0,1,2,4,5,
0,1,2,4,6,
0,1,2,4,7,
0,1,2,5,6,
0,1,2,5,7,
0,1,2,6,7,
0,1,3,4,5,
0,1,3,4,6,
0,1,3,4,7,
0,1,3,5,6,
0,1,3,5,7,
0,1,3,6,7,
0,1,4,5,6,
0,1,4,5,7,
0,1,4,6,7,
0,1,5,6,7,
0,2,3,4,5,
0,2,3,4,6,
0,2,3,4,7,
0,2,3,5,6,
0,2,3,5,7,
0,2,3,6,7,
0,2,4,5,6,
0,2,4,5,7,
0,2,4,6,7,
0,2,5,6,7,
0,3,4,5,6,
0,3,4,5,7,
0,3,4,6,7,
0,3,5,6,7,
0,4,5,6,7,
1,2,3,4,5,
1,2,3,4,6,
1,2,3,4,7,
1,2,3,5,6,
1,2,3,5,7,
1,2,3,6,7,
1,2,4,5,6,
1,2,4,5,7,
1,2,4,6,7,
1,2,5,6,7,
1,3,4,5,6,
1,3,4,5,7,
1,3,4,6,7,
1,3,5,6,7,
1,4,5,6,7,
2,3,4,5,6,
2,3,4,5,7,
2,3,4,6,7,
2,3,5,6,7,
2,4,5,6,7,
3,4,5,6,7,