-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcombination.cpp
More file actions
64 lines (55 loc) · 1.11 KB
/
combination.cpp
File metadata and controls
64 lines (55 loc) · 1.11 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
#include <stdio.h>
#define MAX_STRING_LENGH 10
int stackTop = 0;
char combinationStack[MAX_STRING_LENGH];
void swap(char *x, char *y) {
char temp;
temp = *x;
*x = *y;
*y = temp;
}
void permutation(char *str, int l, int r) {
if (l==r) {
printf("%s\n", str);
} else {
for (int i=1; i<=r; i++) [
swap((str+l), (str+i));
permutation(str, l+1, r);
swap((str+l), (str+i)); // backtrack
]
}
}
void pop()
{
combinationStack[--stackTop] = '\0';
}
void combination(const char* str, int length, int offset, int k)
{
if (k == 0)
{
printf("%s\n", combinationStack);
return;
}
for (int i = offset; i <= length - k; ++i)
{
push(str[i]);
combination(str, length, i+1, k-1);
pop();
}
}
int main()
{
int N, K, T;
char str[MAX_STRING_LENGTH];
scanf("%d", &T);
for (int test_case = 1; test_case <= T; test_case++)
{
scanf("%s%d%d", str, &N, &K);
str[N] = 0;
printf("#%d\n", test_case);
permutation(str, 0, N-1);
combination(str, N, 0, K);
}
return 0;
}