C++ STL 實現全排列與組合

#include <algorithm>
#include <string>
#include <vector>
using namespace std;

template <typename T>
void combine_inner(T &data, int start, int n, int m, 
    int depth, T temp, std::vector<T> &result)
{
    if (depth == m - 1)
    {
        //最內層循環 將temp加入result
        for (int i = start; i < n - (m - depth - 1); ++i)
        {
            temp[depth] = data[i];
            result.emplace_back(temp);
        }
    }
    else
        for (int i = start; i < n - (m - depth - 1); ++i)
        {
            temp[depth] = data[i];//每層輸出一個元素
            combine_inner(data, i + 1, n, m, depth + 1, temp, result);
        }
}

//T可以調入vector<int>, string等,需要支持下標[]操作及size()函數
template <typename T>
std::vector<T> combine(T& data, int m)
{
    if (m <= 0) return{};
    int depth = 0;
    std::vector<T> result;
    T temp(m, 0);
    combine_inner(data, 0, data.size(), m, depth, temp, result);
    return std::move(result);
}

template <typename T>
std::vector<T> permutation(T& data)
{
    std::vector<T> results;
    results.emplace_back(data);
    while (std::next_permutation(data.begin(), data.end()))
    {
        results.emplace_back(data.begin(), data.end());
    }
    return std::move(results);
}

int main()
{
    string str("abcdef");
    auto combine_rets=combine(str, 3);
    printf("rets.size=%d\n", combine_rets.size());

    auto permutation_ret = permutation(str);
    printf("permutation size=%d\n", permutation_ret.size());
    return 0;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章