recursion - 递归 - 打印 uniq 子组
问题描述
我的代码:
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
void printArr(int arr[], int n)
{
for (int i = 0; i < n; i++)
{
printf(" %d ", arr[i]);
}
printf("\n");
}
void tr8Helper(int* arr, int n, int index, int b, int* used)
{
if (index == n )
{
printArr(arr, n);
}
else {
for (int i = 0; i < b; i++) {
arr[index] = i;
tr8Helper(arr, n, index + 1, b, used);
}
}
}
void tr8(int num, int b)
{
int* myArray = (int*)malloc(num * sizeof(int));
int* used = (int*)malloc(b * sizeof(int));
tr8Helper(myArray, num, 0, b, used);
}
int main() {
tr8(3, 3);
}
到目前为止,这是我的代码,这就是我的递归打印 b = 2,n = 3: 此代码 的输出我遇到的麻烦是如何使用“已使用”数组,因此输出将是例如 b= 3 n = 3 请求的输出 我很难考虑如何考虑这个问题,如何从上面考虑。怎么告诉我的recurrion,我用过这个号码,不要再用了。或者只是在打印发生时跳过这一行。请与我分享您的想法和想法,也许还有一些关于您如何处理此类问题的提示
解决方案
Judging by your input and expected output, I believe when you say "unique subgroups" you are referring to k-permutations. If that is the case, then you simply need to employ the used array (which in your code is passed around, but not actually employed). I added three new lines in tr8Helper
; nothing else needs to be changed.
void tr8Helper(int* arr, int n, int index, int b, int* used) {
if (index == n) {
printArr(arr, n);
} else {
for (int i = 0; i < b; i++) {
if (!used[i]) { // (1) do not use i unless it is available
used[i] = 1; // (2) mark i as used so we don't use it twice
arr[index] = i;
tr8Helper(arr, n, index + 1, b, used);
used[i] = 0; // (3) mark i as available so future k-perms can use it
}
}
}
}
推荐阅读
- c - 1000以下所有3或5的倍数之和在C中给出错误答案
- r - R data.table:使用 %like% 和 setkey
- binary - 这个映射是哪个二进制操作?
- mysql - 具有限制的联合查询的行的 rand()
- python - Python:沿着连接点集的线的等距点
- monitoring - 通过 ITRS Geneos 进行 Rundeck 监控
- html - 将文本框放置在图像上
- javascript - 无法在 Angular2 中进行 http 服务调用?
- twig - twig drupal中的拆分url功能
- angular - 在 angular4 中实现 HighCharts-xrange