题目链接:https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=1717
Jahir is a student of NSU (Nice Students’ University). He hates the chapter Permutation & Combinationof the subject Discrete Math. But his teacher give him a assignment to generate all the rcombination of a string. But he is too busy with his new girlfriend to do the assignment himself. Sohe went to Shabuj, a student of CSE (Calculation Science and Engineering) in BUET (BangladeshUniversity of Extraordinary Talents). He asked him to make a program to generate the combinations.But Shabuj is always lazy. He wants your help.
Your task is to print all different r combinations of a string s (a r combination of a string s is acollection of exactly r letters from different positions in s).
There may be different permutations of the same combination; consider only the one that has its rcharacters in non-decreasing order.
The string consists of only lowercase letters. Any letter can occur more than once.
Input
The input is consist of several test cases. Each test case consists of a string s (the length of s is between1 and 30) and an integer r (0 < r ≤ length of s).
Output
For each test case you have to print all different r combinations of s in lexicographic order in separateline. You can assume there are at most 1000 different ones.
Sample Input
abcde 2
abcd 3
aba 2
Sample Output
ab
ac
ad
ae
bc
bd
be
cd
ce
de
abc
abd
acd
bcd
aa
ab
提示
题意:
从该字符串取出r长的子串,以字典序递增顺序输出可能存在子串的全部情况。
思路:
我们可以先对字符串从小到大排序(以ASCII码值)可用map标记子串前缀是否重复,若不重复继续搜索,可以简化到一维数组进行标记。
示例程序
#include <cstdio>
#include <cstring>
#include <string>
#include <map>
#include <algorithm>
using namespace std;
map<string,int>mp;
int n,len;
char s[31],s1[31];
void dfs(int t,int deep)
{
int i;
s1[deep]='\0';
if(mp[s1]==1)
{
return;
}
mp[s1]=1;
if(deep==n)
{
puts(s1);
return;
}
for(i=t+1;len>i;i++)
{
s1[deep]=s[i];
dfs(i,deep+1);
}
}
int main()
{
while(scanf("%s %d",s,&n)!=EOF)
{
mp.clear();
len=strlen(s);
sort(s,s+len);
dfs(-1,0);
}
return 0;
}