说明
该文章只为自己记录学习用
参考
极客时间程序员的数学基础课第7、8讲
排列
代码实现
#include <iostream>
#include <vector>
using namespace std
;
template <typename T
>
class Permutation
{
public:
typedef vector
<T
> Sequence
;
typedef vector
<bool> BitMap
;
public:
vector
<Sequence
> permutation(const Sequence
&sourceSeq
, int m
)
{
if (sourceSeq
.size() < m
|| m
<= 0)
return {};
vector
<Sequence
> totalSeq
;
Sequence targetSeq
;
BitMap
bitMap(sourceSeq
.size(), false);
permutation(sourceSeq
, m
, targetSeq
, totalSeq
, bitMap
);
return totalSeq
;
}
private:
void permutation(const Sequence
&sourceSeq
, int m
, Sequence
&targetSeq
, vector
<Sequence
> &totalSeq
, BitMap
&bitMap
)
{
if (targetSeq
.size() == m
)
{
totalSeq
.push_back(targetSeq
);
return;
}
for (size_t i
= 0; i
< sourceSeq
.size(); i
++)
{
if (bitMap
[i
])
continue;
targetSeq
.push_back(sourceSeq
[i
]);
bitMap
[i
] = true;
permutation(sourceSeq
, m
, targetSeq
, totalSeq
, bitMap
);
targetSeq
.pop_back();
bitMap
[i
] = false;
}
}
};
int main()
{
vector
<int> seq
= {1, 2, 3, 4, 5};
auto result
= Permutation
<int>().permutation(seq
, 3);
cout
<< result
.size() << endl
;
for (int i
= 0; i
< result
.size(); i
++)
{
cout
<< '[';
int j
= 0;
for (; j
< result
[i
].size() - 1; j
++)
{
cout
<< result
[i
][j
] << ',';
}
cout
<< result
[i
][j
];
cout
<< ']' << endl
;
}
return 0;
}
测试结果
组合
代码实现
#include <iostream>
#include <vector>
using namespace std
;
template <typename T
>class Combination
{
public:
typedef vector
<T
> Sequence
;
public:
vector
<Sequence
> combination(const Sequence
&sourceSeq
, int m
)
{
if (m
<= 0 || m
> sourceSeq
.size())
return {};
vector
<Sequence
> totalSeq
;
Sequence targetSeq
;
combination(sourceSeq
, m
, 0, targetSeq
, totalSeq
);
return totalSeq
;
}
private:
void combination(const Sequence
&sourceSeq
, int m
, int cur
, Sequence
&targetSeq
, vector
<Sequence
> &totalSeq
)
{
if (targetSeq
.size() == m
)
{
totalSeq
.push_back(targetSeq
);
return;
}
for (int i
= cur
; i
< sourceSeq
.size(); i
++)
{
targetSeq
.push_back(sourceSeq
[i
]);
combination(sourceSeq
, m
, i
+ 1, targetSeq
, totalSeq
);
targetSeq
.pop_back();
}
}
};
int main()
{
vector
<int> seq
= {1, 2, 3, 4, 5};
auto result
= Combination
<int>().combination(seq
, 3);
cout
<< result
.size() << endl
;
for (int i
= 0; i
< result
.size(); i
++)
{
cout
<< '[';
int j
= 0;
for (; j
< result
[i
].size() - 1; j
++)
{
cout
<< result
[i
][j
] << ',';
}
cout
<< result
[i
][j
];
cout
<< ']' << endl
;
}
return 0;
}
测试结果
转载请注明原文地址: https://lol.8miu.com/read-20505.html