|
发表于 2022-6-17 20:23:17
|
显示全部楼层
- #include <stdio.h>
- void Combine(int n, int r, char a[], int b[], int R) {
- if(r == 0) {
- int i = 0;
- for(i = 0; i < R; i++) {
- //printf("%c ", a[b[i]]);
- printf("%hhd ", a[b[i]]); // 这里不是%c吧?应该是%hhd吧?
- // a数组中的元素类型是signed char
- // signed char应该用%hhd
- }
- printf("\n");
- } else {
- // 看不懂你这个for循环是在做什么
- for(int j = n; j >= r; j--) {
- b[r - 1] = j - 1;
- Combine(j - 1, r - 1, a, b, R + 1);
- }
- }
- }
- int main() {
- int n = 5, r = 3, R = 0;
- char a[5] = {1, 2, 3, 4, 5};
- int b[5];
- Combine(n, r, a, b, R);
- }
复制代码
是要下面这样的效果吗?
- #include <stdio.h>
- void Combine(int n, int r, const int a[const], int b[], int c[], int R) {
- if(R >= r) {
- for(size_t i = 0; i < R; ++i) {
- printf("%d ", b[i]);
- }
- puts("");
- return;
- }
- for(size_t i = 0; i < n; ++i) {
- if(c[i]) continue;
- c[i] = 1;
- b[R] = a[i];
- Combine(n, r, a, b, c, R + 1);
- c[i] = 0;
- }
- }
- int main() {
- int n = 5, r = 3, R = 0;
- int a[5] = {1, 2, 3, 4, 5};
- int b[5];
- int c[5] = {0};
- Combine(n, r, a, b, c, R);
- }
复制代码
- $ ./main
- 1 2 3
- 1 2 4
- 1 2 5
- 1 3 2
- 1 3 4
- 1 3 5
- 1 4 2
- 1 4 3
- 1 4 5
- 1 5 2
- 1 5 3
- 1 5 4
- 2 1 3
- 2 1 4
- 2 1 5
- 2 3 1
- 2 3 4
- 2 3 5
- 2 4 1
- 2 4 3
- 2 4 5
- 2 5 1
- 2 5 3
- 2 5 4
- 3 1 2
- 3 1 4
- 3 1 5
- 3 2 1
- 3 2 4
- 3 2 5
- 3 4 1
- 3 4 2
- 3 4 5
- 3 5 1
- 3 5 2
- 3 5 4
- 4 1 2
- 4 1 3
- 4 1 5
- 4 2 1
- 4 2 3
- 4 2 5
- 4 3 1
- 4 3 2
- 4 3 5
- 4 5 1
- 4 5 2
- 4 5 3
- 5 1 2
- 5 1 3
- 5 1 4
- 5 2 1
- 5 2 3
- 5 2 4
- 5 3 1
- 5 3 2
- 5 3 4
- 5 4 1
- 5 4 2
- 5 4 3
- $
复制代码 |
|