본문 바로가기
Computer Science

Permutation & Combination

by OKOK 2019. 1. 16.

1. okay

2. 코드 분석 능력도 필요함

3. 코드 보고 어떻게 돌아가는지 확인해야 함 


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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
#include <stdio.h>
 
#define MAX_STRING_LENGTH 10
 
int stackTop = 0;
char combinationStack[MAX_STRING_LENGTH];
 
void swap(char *x, char *y)
{
    char temp;
    temp = *x;
    *= *y;
    *= temp;
}
 
void permutation(char *str, int l, int r)
{
    if (l == r)
    {
        printf("%s\n", str);
    }
    else
    {
        for (int i = l; i <= r; i++)
        {
            swap((str + l), (str + i));
            permutation(str, l + 1, r);
            swap((str + l), (str + i)); //backtrack
        }
    }
}
 
void push(char ch)
{
    combinationStack[stackTop++= ch;
    combinationStack[stackTop] = '\0';
}
 
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()
{
    freopen("input.txt""r", stdin);
    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;
}
cs

 


'Computer Science' 카테고리의 다른 글

BFS Algo  (0) 2019.01.16
DFS Algo  (0) 2019.01.16
Dynamic programming  (0) 2019.01.16
BFS queue  (0) 2019.01.15
Deque  (0) 2019.01.14

댓글