-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.cpp
85 lines (66 loc) · 1.26 KB
/
main.cpp
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
#include <iostream>
#include <string>
#include <vector>
using namespace std;
void swapChar(char* p1, char* p2)
{
char tmp = *p1;
*p1 = *p2;
*p2 = tmp;
}
void PermulationDFS(char* str, int idx)
{
if (idx == strlen(str))
{
cout << str << endl;
return;
}
for (int i = idx; i < strlen(str); ++i)
{
if (i > idx && str[i] == str[i - 1])
continue;
swapChar(str + idx, str + i); //不用另外开辟内存
PermulationDFS(str, idx + 1);
swapChar(str + idx, str + i);
}
}
void Permulation(char* str)
{
if (str == NULL || strlen(str) == 0)
return;
PermulationDFS(str, 0);
}
void CombinationDFS(char* str, int idx, string& res)
{
if (res.size() > 0)
cout << res << endl;
if (idx == strlen(str))
return;
for (int i = idx; i < strlen(str); ++i)
{
if (i > idx && str[i] == str[i - 1]) //防止重复
continue;
res.push_back(str[i]);
CombinationDFS(str, i + 1, res); //直接从i+1开始,避免重复
res.pop_back();
}
}
void Combination(char* str)
{
if (str == NULL || strlen(str) == 0)
return;
string res;
CombinationDFS(str, 0, res);
}
int main()
{
char str[] = {"aa"};
cout << "original:" << endl;
cout << str << endl;
cout << "permulation:" << endl;
Permulation(str);
cout << "combination:" << endl;
Combination(str);
int aa;
cin >> aa;
}