How do I get all permutations of xPy?

后端 未结 3 721
小蘑菇
小蘑菇 2021-01-19 05:07

I\'d like to calculate all the permutations of size Y of a set of size X. That is if I had (1,2,3) and want all permutations of size 2, 3P2, it would be (1,2) (1,3) (2,1) (

3条回答
  •  情歌与酒
    2021-01-19 05:42

    You can get the combinations by using std::next_permutation() on a vector of flags. Taking your example of picking 2 elements from (1,2,3), start your vector as (false, true, true). Repeating next_permutation() on this will give you (true, false, true) then (true, true, false), before starting over.

    Since you want permutations not combinations, map each combination to the set of actual elements (e.g. (true, false, true) becomes (1, 3)) and then generate all the permutations of these using next_permutation() again.

提交回复
热议问题