给定一个向量,如何找到该向量的所有子集和的原始索引

Given a vector, how to find all subsets of the vector and the original indices of

本文关键字:向量 子集 索引 原始 和的 一个 何找      更新时间:2023-10-16

给定一个向量,如何从该向量中找到伴随原始索引的向量的所有子集?

例如,给定矢量

vector<float> numbers {1.3, 0.5, 2.4};

获取子集:

{}, {1.3}, {0.5}, {2.4}, {1.3, 2.4}, {0.5, 2.4}, {1.3, 0.5}, {1.3, 0.5, 2.4}

以及每个子集的相应索引:

{}, {0}, {1}, {2}, {0, 2}, {1, 2}, {0, 1}, {0, 1, 2}.

这是家庭作业吗?:-P

以下函数将生成索引子集indices参数只是一个临时的临时变量。

void getIndexSubsets(
int l, int u, std::vector<int>* indices, 
std::vector<std::vector<int>>* result) {
if (l == u) {
result->push_back(*indices);
} else {
int next = l + 1;
getIndexSubsets(next, u, indices, result);
indices->push_back(l);
getIndexSubsets(next, u, indices, result);
indices->pop_back();
}
}

它是这样使用的:

std::vector<float> numbers{1.3, 0.5, 2.4};
std::vector<int> indices;
std::vector<std::vector<int>> indexResult;
getIndexSubsets(0, numbers.size(), &indices, &indexResult);

索引子集将在indexResult中输出。给定索引子集,我们可以使用以下函数计算值子集:

std::vector<std::vector<float>> getValueSubsets(
const std::vector<float>& srcValues,
const std::vector<std::vector<int>>& src) {
std::vector<std::vector<float>> dst;
for (const auto& inds: src) {
std::vector<float> x;
for (auto i: inds) {
x.push_back(srcValues[i]);
}
dst.push_back(x);
}
return dst;
}

这样调用:

std::vector<std::vector<float>> valueResult = getValueSubsets(numbers, indexResult);

完整的解决方案如下所示。

#include <iostream>
#include <vector>
void getIndexSubsets(
int l, int u, std::vector<int>* indices, 
std::vector<std::vector<int>>* result) {
if (l == u) {
result->push_back(*indices);
} else {
int next = l + 1;
getIndexSubsets(next, u, indices, result);
indices->push_back(l);
getIndexSubsets(next, u, indices, result);
indices->pop_back();
}
}
std::vector<std::vector<float>> getValueSubsets(
const std::vector<float>& srcValues,
const std::vector<std::vector<int>>& src) {
std::vector<std::vector<float>> dst;
for (const auto& inds: src) {
std::vector<float> x;
for (auto i: inds) {
x.push_back(srcValues[i]);
}
dst.push_back(x);
}
return dst;
}
template <typename T>
std::ostream& operator<<(std::ostream& s, const std::vector<T>& src) {
s << "{";
bool f = true;
for (auto x: src) {
s << (f? "" : " ") << x;
f = false;
}
s << "}";
return s;
}
int main() {
std::vector<float> numbers{1.3, 0.5, 2.4};
std::vector<int> indices;
std::vector<std::vector<int>> indexResult;
getIndexSubsets(0, numbers.size(), &indices, &indexResult);
std::vector<std::vector<float>> valueResult = getValueSubsets(numbers, indexResult);
for (int i = 0; i < indexResult.size(); i++) {
std::cout << "Subset inds=" << indexResult[i] << " values=" << valueResult[i] << std::endl;
}
return 0;
}

执行时,它将输出以下内容:

Subset inds={} values={}
Subset inds={2} values={2.4}
Subset inds={1} values={0.5}
Subset inds={1 2} values={0.5 2.4}
Subset inds={0} values={1.3}
Subset inds={0 2} values={1.3 2.4}
Subset inds={0 1} values={1.3 0.5}
Subset inds={0 1 2} values={1.3 0.5 2.4}