开发者

different length permutations [duplicate]

开发者 https://www.devze.com 2023-02-18 06:13 出处:网络
This question already has answers here: Closed 11 years ago. Possible Duplicate: Algorithm to return all combinations of k elements from n
This question already has answers here: Closed 11 years ago.

Possible Duplicate:

Algorithm to return all combinations of k elements from n

What I want to do is generate all 1-9 permutations of different length. For example all permutations of length one would simply be {1}, {2}, {3}, {4} .. and so on. Permutations of length two would be: {1,2}, {1,3}, {1,4} .. So far I've been using std::next_permutation(), however it won't do the job in this case.

Is there any way to solve this pro开发者_Python百科blem without using recursion? If not and you're providing any code I would really appreciate if you would explain to me, because I'm really struggling with recursion right now, especially with implementing recursive solutions myself. Thanks in advance.


The approach I would use starts from hakmem 175 and that is finding the next higher number with the same number of bits. So let's say that you code in one int you 10 numbers (from bit 0 to bit 9) That means that you have to loop from 1 to 10 and prime your start int with the first number that will approximate your pair.

ex: for {1},{2} ... the start int would be 2^0 for {1,2} {1,3} ... the start int would be 2^0+2^1 and so on.

after that you have to make a method that would interpret the number (check if a bit is set then the corresponding number will appear in the sequence).

after that call hakmems method for the next number:

unsigned nexthi(unsigned a) {
  unsigned c = (a & -a);
  unsigned r = a+c;
  return (((r ^ a) >> 2) / c) | r);
}

and continue the loop until no numbers remain.

and go to the next number of bits (1->10)

I suggest looking to hakmem method for you to understand how it works, the implementation is easy if you know a few things about bits.


void permute(std::vector<int>& digits, int length) {
    if (length == 0) {
        std::cout << "{";
        for (int i = 0; i < digits.length; i++) {
            std::cout << digits[i] << ",";
        }
        std::cout << "}" << std::endl;
        return;
    }

    for (int i = 0; i < 9; i++) {
        std::vector<int> newDigits(digits);
        newDigits.push_back(i);
        permute(newDigits, length -1);
    }
}

Call this within main as

std::vector<int> digits;
permute(digits, 10); // For 10 digit permutations. 

Now if you want to get permutations of length 1,2 ... n, then all you have to do is put the permute function inside a loop.

Note that this is not the most efficient of implementations. But I suppose this should illustrate the recursion clearly.

0

精彩评论

暂无评论...
验证码 换一张
取 消