【问题标题】:Find all combinations without repetition找到所有不重复的组合
【发布时间】:2013-11-03 09:54:41
【问题描述】:

我必须在 C++ 应用程序中找到所有使用 3 个整数且不重复的组合。

当我指定我有多少个整数时,我可以计算出将有多少个组合。

unsigned int combinations(unsigned int n){
    return ((n/3) * ((n-1)/2) * (n-2));
}

但是我怎样才能添加到vector 这些所有组合? f.e 使用:1,2,3,4:123,234,124,134。顺序不重要,123321 相同。

【问题讨论】:

  • 使用 std::vector::push_back(...) 函数?
  • 但是我如何计算这些:123,234,124,134

标签: c++ combinations


【解决方案1】:
#include <vector>

using namespace std;

struct tuple3 {
    int a, b, c;   
    tuple3(int a, int b, int c) : a(a), b(b), c(c) {}
};

vector<tuple3> combinations3(vector<int> n) {
    vector<tuple3> ret;
    for(vector<int>::const_iterator it1 = n.begin(); it1 < n.end(); it1++) {
        for(vector<int>::const_iterator it2 = n.begin(); it2 < it1; it2++) {
            for(vector<int>::const_iterator it3 = n.begin(); it3 < it2; it3++) {
                ret.push_back(tuple3(*it1, *it2, *it3));
            }
        }
    }
    return ret;
}

致未来的读者:如果可以,请使用 C++11 std::arraystd::tuple。我没有在这里,因为它在许多编译器上尚不可用或默认。

【讨论】:

  • 感谢此代码,但它也以另一种顺序(重复)计算所有组合。检查我的第一篇文章:f.e 使用:1,2,3,4:123,234,124,134。顺序不重要,123321 相同。
  • 另外,排在第二位的是:我认为应该是 it2++ 而不是 it1++
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-06-30
  • 1970-01-01
  • 1970-01-01
  • 2013-03-03
  • 2020-10-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多