-
Notifications
You must be signed in to change notification settings - Fork 0
/
permutations2.c
139 lines (98 loc) · 2.24 KB
/
permutations2.c
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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <limits.h>
#include <time.h>
#include "lib/helpers.h"
#include "lib/hash.h"
int PermutationsHelper(char *str, char *prefix)
{
int index = 0, len = strlen(str), cn = 0;
if (len == 0)
{
printf("%s\n", prefix);
return 1;
}
while (str[index] != '\0')
{
char *substr = StrConcat(Substring(str, 0, index - 1), Substring(str, index + 1, len - 1));
char *sub_prefix = StrConcatChar(prefix, str[index]);
// printf("substr %s prefix %s\n", substr, sub_prefix);
cn += PermutationsHelper(substr, sub_prefix);
++index;
}
return cn;
}
int Permutations(char *str)
{
return PermutationsHelper(str, NULL);
}
// ====================================================================
void HashDump(struct Hash *hash)
{
struct ListNode *head = &hash->list_nodes, *p = NULL;
for (p = head->next; p != head; p = p->next)
{
struct HashNode *hash_node = p->container;
int *key = hash_node->key;
int *freq = hash_node->val;
printf("%c : %d\n", *key, *freq);
}
}
void PrepareHash(struct Hash *hash, char *str)
{
char *c = str;
while (*c != '\0')
{
int tmp = *c;
int *freq = HashGet(hash, &tmp);
if (freq == NULL)
{
int *key = calloc(1, sizeof(int));
*key = tmp;
freq = calloc(1, sizeof(int));
*freq = 0;
HashInsert(hash, key, freq);
}
++*freq;
++c;
}
// HashDump(hash);
}
int PermutationsDupHelper(struct Hash *hash, int len, char *prefix)
{
int cn = 0;
struct ListNode *head = &hash->list_nodes, *p = NULL;
if (len == 0)
{
printf("%s\n", prefix);
return 1;
}
for (p = head->next; p != head; p = p->next)
{
struct HashNode *hash_node = p->container;
int *key = hash_node->key;
int *freq = hash_node->val;
if (*freq == 0)
continue;
--*freq;
cn += PermutationsDupHelper(hash, len - 1, StrConcatChar(prefix, *key));
++*freq;
}
return cn;
}
int PermutationsDup(char *str)
{
int len = strlen(str);
struct Hash hash_freq;
HashInit(&hash_freq, FuncIntToInt, FuncIntCompare);
PrepareHash(&hash_freq, str);
return PermutationsDupHelper(&hash_freq, len, NULL);
}
int main(int argc, char *argv[])
{
char str[] = "adac";
printf("%d\n", Permutations(str));
printf("(dedup) %d\n", PermutationsDup(str));
return 0;
}