zoukankan      html  css  js  c++  java
  • (六)排列Permutation-组合Combination

    1. 排列

    1.1 std::next_permutation

    使用STL的std::next_permutation函数

    void PermutationTest()
    {
        string s = "abc";
        cout << s << endl;
        while (std::next_permutation(s.begin(), s.end())){
            cout << s << endl;
        }
    }
    

    1.2 递归+回溯

    参考:

    算法思路:
    (1)n个元素的全排列=(n-1个元素的全排列)+(另一个元素作为前缀);
    (2)出口:如果只有一个元素的全排列,则说明已经排完,则输出数组;
    (3)不断将每个元素放作第一个元素,然后将这个元素作为前缀,并将其余元素继续全排列,等到出口,出口出去后还需要还原数组;

    void Permutation(int first, int last, vector<int> &v)
    {
        if (first == last){
            for (auto e : v){
                cout << e << " ";
            }
            cout << endl;
            return;
        }
    
        for (int i = first; i <= last; ++i){
            Swap(first, i, v);
            Permutation(first + 1, last, v);
            Swap(first, i, v);
        }
    }
    
    void PermutationTest()
    {
        vector<int> v = { 1, 2, 3, 4, 5 };
        Permutation(0, 4, v);
    }
    

    2. 组合

    2.1 STL的next_permutation函数

    void CombinationTest()
    {
        std::vector<int> v = { 1, 2, 3, 4, 5, 6, 7 };
        std::vector<int> selector = { 0, 0, 0, 0, 1, 1, 1 };
        int count = 0;
        do{
            cout << ++count << ": ";
            for (int i = 0; i < v.size(); ++i){
                if (selector[i] == 1){
                    cout << v[i] << " ";
                }
            }
            cout << endl;
        } while (next_permutation(selector.begin(), selector.end()));
    }
    

    2.2 递归

    参考:

    void Combination(const std::vector<int> &v, int n, int m, std::vector<int> &result)
    {
        if (m == 0){
            std::for_each(result.begin(), result.end(), [](int a){std::cout << a << " "; });
            std::cout << endl;
            return;
        }
    
        for (int i = n; i >= m; --i){
            result.push_back(v[i - 1]);
            Combination(v, i - 1, m - 1, result);
            result.pop_back();
        }
    }
    
    void CombinationTest()
    {
        const std::vector<int> v = { 1, 2, 3, 4, 5 };
        int n = 5;
        int m = 3;
        std::vector<int> result;
        Combination(v, n, m, result);
    }
    
  • 相关阅读:
    测试中发现哪些bug
    兼容性测试
    接口测试基础
    Java基础概念
    Linux基础命令
    Selenium笔记
    常见软件测试类型分类
    性能测试类型
    网络基础题目
    常见测试方法
  • 原文地址:https://www.cnblogs.com/walkinginthesun/p/9850875.html
Copyright © 2011-2022 走看看