How would you calculate all possible permutations of 0 through N iteratively?

后端 未结 10 2631
一向
一向 2020-12-04 15:47

I need to calculate permutations iteratively. The method signature looks like:

int[][] permute(int n)

For n = 3 for example, the r

10条回答
  •  长情又很酷
    2020-12-04 16:32

    The algorithm for stepping from one permutation to the next is very similar to elementary school addition - when an overflow occurs, "carry the one".

    Here's an implementation I wrote in C:

    #include 
    
    //Convenience macro.  Its function should be obvious.
    #define swap(a,b) do { \
            typeof(a) __tmp = (a); \
            (a) = (b); \
            (b) = __tmp; \
        } while(0)
    
    void perm_start(unsigned int n[], unsigned int count) {
        unsigned int i;
        for (i=0; i0 && n[i-1] >= n[i]; i--);
        tail = i;
    
        if (tail > 0) {
            /* Find the last item from the tail set greater than
                the last item from the head set, and swap them.
                Example: 0 3* (5 4* 2 1)
                Becomes: 0 4* (5 3* 2 1) */
            for (j=count-1; j>tail && n[j] <= n[tail-1]; j--);
    
            swap(n[tail-1], n[j]);
        }
    
        /* Reverse the tail set's order */
        for (i=tail, j=count-1; i

提交回复
热议问题