簡體   English   中英

大小 n 算法的所有可能組合和排列

[英]All possible combinations and permutations of size n algorithm

我試圖找出一種算法,從大小為n的數組中獲得大小為k的所有可能組合和排列。

讓我們舉個例子:

輸入:

n = 3 => [1, 2, 3]

Output 應該是:

k = 1 => [[1], [2], [3]]
k = 2 => [[1, 2], [1, 3], [2, 3], [2, 1], [3, 1], [3, 2]]
k = 3 => [[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1 ,2], [3, 2, 1]]

我首先查看QuickPerm 算法,但它給出了數組大小的所有可能排列:

如果我們 go 回到我們的例子,QuickPerm 算法給出這個 output:

[[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1 ,2], [3, 2, 1]].

您的任務(所有組合的所有排列)可以使用常規遞歸 function(正如我在下面所做的那樣)輕松解決,無需任何花哨的算法。

在線試用!

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

void GenCombPerm(size_t n, size_t k, auto const & outf) {
    std::vector<bool> used(n);
    std::vector<size_t> path;
    std::function<void()> Rec =
        [&]{
            if (path.size() >= k) {
                outf(path);
                return;
            }
            for (size_t i = 0; i < used.size(); ++i) {
                if (used[i])
                    continue;
                used[i] = true;
                path.push_back(i);
                Rec();
                path.pop_back();
                used[i] = false;
            }
        };
    Rec();
}

int main() {
    std::vector<size_t> a = {1, 2, 3};
    GenCombPerm(a.size(), 2, [&](auto const & v){
        std::cout << "[";
        for (auto i: v)
            std::cout << a[i] << ", ";
        std::cout << "], ";
    });
}

Output:

[1, 2, ], [1, 3, ], [2, 1, ], [2, 3, ], [3, 1, ], [3, 2, ], 
class CombinationsPermutation {
public:
    explicit CombinationsPermutation(size_t n, size_t k)
        : n { n }
    {
        indexes.resize(k);
        reset();
    }

    void reset()
    {
        std::iota(indexes.begin(), indexes.end(), 0);
    }

    const std::vector<size_t>& get() const
    {
        return indexes;
    }

    bool next()
    {
        if (std::next_permutation(indexes.begin(), indexes.end())) {
            return true;
        }
        auto it = indexes.rbegin();
        auto max_index = n - 1;
        while (it != indexes.rend() && *it == max_index) {
            --max_index;
            ++it;
        }
        if (it != indexes.rend()) {
            std::iota(it.base() - 1, indexes.end(), *it + 1);
            return true;
        }
        reset();
        return false;
    }

private:
    size_t n;
    std::vector<size_t> indexes;
};

https://godbolt.org/z/dex634fY1

您可以創建給定數組的所有子集,然后對所有子集應用 quickPerm 算法。

[1,2,3] 的子集將是

[]
[1], [2], [3]
[1,2], [2,3], [3,1]
[1,2,3]

現在,如果您對所有這些子集應用 quickPerm,您將得到:

[]
[1], [2], [3]
[1,2], [2,1]
[2,3], [3,2]
[3,1], [1,3],
[1,2,3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1 ,2], [3, 2, 1]

您可以使用這些向量的長度來合並結果。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM