【发布时间】:2017-12-02 22:30:55
【问题描述】:
假设我们有两个孩子想要获得相同的数字或硬币(硬币名义上的 1、2、6、12)。孩子们不在乎价值。 我想在两个孩子之间共享的排列容器示例:
{1, 1, 1, 1, 1, 1},
{1, 1, 2, 2},
{1, 2, 1, 2},
{1, 2, 2, 1},
{2, 1, 1, 2},
{2, 1, 2, 1},
{2, 2, 1, 1}
现在我想要没有重复的集合:
child A child B
2 2 1 1
2 1 2 1
1 1 2 2
1 1 1 1 1 1
排列是错误的:
1 2 1 2
1 2 2 1
2 1 1 2
因为
child A child B
1 2 1 2
是排列
child A child B
2 1 2 1
我们已经拥有了。这些集合:1 2 2 1 和 2 1 1 2 也是排列组合。
我的解决方案在这里,适用于该特定输入,但如果你添加更多具有不同名义的硬币,它就不会!
#include <iostream>
#include <vector>
#include <unordered_set>
using namespace std;
int main()
{
vector<vector<int>> permutations =
{
{1, 1, 1, 1, 1, 1},
{1, 1, 2, 2},
{1, 2, 1, 2},
{1, 2, 2, 1},
{2, 1, 1, 2},
{2, 1, 2, 1},
{2, 2, 1, 1}
};
vector<pair<unordered_multiset<int>, unordered_multiset<int>>> childSubsets;
for(const auto ¤tPermutation : permutations)
{
size_t currentPermutationSize = currentPermutation.size();
size_t currentPermutationHalfSize = currentPermutationSize / 2;
//left
unordered_multiset<int> leftSet;
for(int i=0;i<currentPermutationHalfSize;++i)
leftSet.insert(currentPermutation[i]);
bool leftSubsetExist = false;
for(const auto &subset : childSubsets)
{
if(subset.first == leftSet)
{
leftSubsetExist = true;
break;
}
}
//right
unordered_multiset<int> rightSet;
for(int i = currentPermutationHalfSize; i < currentPermutationSize; ++i)
rightSet.insert(currentPermutation[i]);
bool rightSubsetExist = false;
for(const auto &subset : childSubsets)
{
if(subset.second == rightSet)
{
rightSubsetExist = true;
break;
}
}
//summarize
if(!leftSubsetExist || !rightSubsetExist) childSubsets.push_back({leftSet, rightSet});
}
cout << childSubsets.size() << endl;
}
如何更改解决方案以使其最优且不那么复杂?
【问题讨论】:
-
如何删除特定数据集中的重复项? -- 首先不要存储重复项。使用
std::unordered_set。 -
std::unordered_set 不允许包含重复项。在该算法中可能有例如一组 2,2 个。
标签: c++ algorithm c++11 time-complexity