Determine The combination
Input: standard input
Output: standard output
Time Limit: 1 second
Jahir is a student of NSU (Nice Students' University ). He hates the chapterPermutation& Combination of the subject Discrete Math. But his teacher givehim a assignment to generate
all the r combination of a string. But heis too busy with his new girlfriend to do the assignment himself. So hewent to Shabuj, a student ofCSE ( Calculation Science and Engineering ) in
BUET (Bangladesh University of Extraordinary Talents ). He asked himto make a program to generate the combinations. But Shabuj is alwayslazy. He wants your help.
Your task is to print alldifferentr combinations of astring
s (a rcombination of a string s isacollection of exactly rletters from different positions in s).
There may be different permutations of the same combination; consideronly the one that has its rcharacters in non-decreasing order.
The string consists of only lowercase letters. Any letter can occurmore than once.
Input
The input isconsist of several test cases. Each test case consists of a strings( the length of
s is between 1 and 30 ) andan integer
r ( 0 < r <= length of s).
Output
For each test case you have to print all different r combinations of sin lexicographic order in separate line. You can assume there are atmost 1000 different ones.
abcde 2
abcd 3
aba 2
SampleOutput
ab
ac
ad
ae
bc
bd
be
cd
ce
de
abc
abd
acd
bcd
aa
ab
#include <cstdio>
#include <cstring>
#include <string>
#include <algorithm>
#include <cctype>
using namespace std;
const int N = 26;
string s;
int r;
int cnt[N];
int number[N], n;
char ch[N];
bool input();
void solve();
void dfs(int cur, int dep, string s);
int main()
{
#ifndef ONLINE_JUDGE
freopen("d:\\OJ\\uva_in.txt", "r", stdin);
#endif
while (input()) {
solve();
}
return 0;
}
bool input()
{
char buf[N + 10];
if (scanf("%s%d", buf, &r) != 2) return false;
s = buf;
sort(s.begin(), s.end());
memset(cnt, 0x00, sizeof(cnt));
for (size_t i = 0; i < s.length(); i++) {
cnt[s[i] - 'a']++;
}
n = 0;
for (int i = 0; i < N; i++) {
if (cnt[i] != 0) {
number[n] = cnt[i];
ch[n++] = i + 'a';
}
}
return true;
}
void dfs(int cur, int dep, string s)
{
if (dep == r) {
printf("%s\n", s.c_str());;
return;
}
for (int i = cur; i < n; i++) {
if (number[i] > 0) {
number[i]--;
string tmp = s;
tmp.append(1, ch[i]);
dfs(i, dep + 1, tmp);
number[i]++;
}
}
}
void solve()
{
dfs(0, 0, "");
}