【问题标题】:All combination of a char * in c?c中char *的所有组合?
【发布时间】:2019-07-23 23:32:18
【问题描述】:

假设我在 C 中有以下字符串:

char * str = "1234";

现在我需要所有可能的字母组合:

12
13
14

21
23
24

...

123
124
132
134
142
143

213
214
231
234
241
243
...

412
413
421
423
431
432

我查找了解决方案并找到了排列。但排列并不是我想要的。 有人有解决这个问题的方法吗?

【问题讨论】:

  • 您正在寻找“powerset”
  • 究竟是什么问题?你还没有清楚地说明确切你想要什么。例如,您如何计算“11223344”?
  • 或者更确切地说,似乎是powerset中元素的排列。
  • 看起来您需要所有子集的所有排列?
  • 查看 stackoverflow.com/questions/7441571/… 以查找所有组合。

标签: c algorithm permutation


【解决方案1】:

虽然没有按字典顺序排序,但以下代码将打印原始字符串中字符的幂集元素的所有排列。

#include <stdio.h>
#include <string.h>

void swap(char* arr, int i, int j) {
    char t = arr[i];
    arr[i] = arr[j];
    arr[j] = t;
}

void permute(char *str, int i, int n) {
    for (int j = i; j < n; j++) {
        swap(str, i, j);
        if (!str[i]) {
            printf("%s\n", str);
        } else {
            permute(str, i+1, n);
        }
        swap(str, i, j); 
    }
} 

int main(void) {
    char str[] = "1234";
    permute(str, 0, strlen(str) + 1);
}

使用贝尔算法,我生成原始字符串中字符的所有排列包括空终止符。然后,我加入一个条件,在传递空终止符时打印并中止当前排列,以防止打印原始字符的同一子集的重复。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-12-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-04
    • 1970-01-01
    相关资源
    最近更新 更多