Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> การเขียนโปรแกรม C

สร้างสตริงทุกความยาวจากตัวอักษรที่กำหนด ในภาษา C

สร้างสตริงทุกความยาวจากชุดตัวอักษรที่กำหนด (permutations ของทุก subset)

ตัวอย่าง

Input: "ABC"

Output: A, B, C, AB, BA, AC, CA, BC, CB, ABC, ACB, BAC, BCA, CAB, CBA

อัลกอริทึม

ใช้ bitmask 1 ถึง 2ⁿ-1 สำหรับแต่ละ subset สร้างสตริงย่อย แล้วหา permutation ทั้งหมดด้วย next_permutation

โค้ดตัวอย่าง (C++)

#include <iostream>
#include <algorithm>
#include <cmath>
using namespace std;

void printAllStrings(string str) {
    int n = str.size();
    int total = pow(2, n);
    for (int mask = 1; mask < total; mask++) {
        string sub = "";
        for (int j = 0; j < n; j++)
            if (mask & (1<