給定一個字符串,輸出其所有非空子集(組合),即從中選取 1 到 n 個字符的所有可能排列。例如 "abc" 輸出 a, b, c, ab, ac, bc, abc。
對於字符串的第一個字符,有兩種選擇:
n-1 個字符,需再選 m-1 個。n-1 個字符,仍需選 m 個。終止條件:m == 0(輸出當前組合)或字符串為空(返回)。
#include <iostream>
#include <vector>
#include <cstring>
using namespace std;
void combination(const char* str, int m, vector<char>& path) {
if (m == 0) {
for (char c : path) cout << c;
cout << '\n';
return;
}
if (*str == '\0') return;
// 選擇當前字符
path.push_back(*str);
combination(str + 1, m - 1, path);
path.pop_back();
// 不選擇當前字符
combination(str + 1, m, path);
}
void all_combinations(const char* str) {
if (!str) return;
int len = strlen(str);
vector<char> path;
for (int m = 1; m <= len; ++m) {
combination(str, m, path);
}
}
int main() {
char s[] = "abc";
all_combinations(s);
return 0;
}
O(2^n),空間 O(n)(遞歸棧 + 路徑存儲)。next_permutation。if (i > start && str[i] == str[i-1]) continue;)。