suzuzusu日記

(´・ω・`)

重複あり組み合わせ C++11

メモとして

#include<functional>
#include<vector>
#include<iostream>

using namespace std;

template<class T>
vector<vector<T>> combinations_with_replacement(const vector<T> n, int r) {
    vector<vector<T>> result;

    function<void(const vector<T>, int, vector<T>, vector<vector<T>>*)> f = [&f](const vector<T> n, const int r, const vector<T> acc, vector<vector<T>>* result) {
        if (r <= 0) {
            (*result).push_back(acc);
            return;
        }
        for (auto itr = n.begin(); itr != n.end(); ++itr) {
            vector<T> tmp_acc = vector<T>(acc);
            tmp_acc.push_back(*itr);
            f(n, r - 1, tmp_acc, result);
        }
    };

    f(n, r, {}, &result);
    return result;
}

int main(){
    auto result = combinations_with_replacement<int>({1, 2, 3, 4}, 2);
    for (auto i : result) {
        for (auto j : i) {
            cout << j << " ";
        }
        cout << endl;
    }
    return 0;
}

/*
1 1
1 2
1 3
1 4
2 1
2 2
2 3
2 4
3 1
3 2
3 3
3 4
4 1
4 2
4 3
4 4
*/