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

后端 未结 10 2617
一向
一向 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:34

    I found Joey Adams' version to be the most readable, but I couldn't port it directly to C# because of how C# handles the scoping of for-loop variables. Hence, this is a slightly tweaked version of his code:

    /// 
    /// Performs an in-place permutation of , and returns if there 
    /// are any more permutations remaining.
    /// 
    private static bool NextPermutation(int[] values)
    {
        if (values.Length == 0)
            throw new ArgumentException("Cannot permutate an empty collection.");
    
        //Find all terms at the end that are in reverse order.
        //  Example: 0 3 (5 4 2 1) (i becomes 2)
        int tail = values.Length - 1;
        while(tail > 0 && values[tail - 1] >= values[tail])
            tail--;
    
        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)
            int index = values.Length - 1;
            while (index > tail && values[index] <= values[tail - 1])
                index--;
    
            Swap(ref values[tail - 1], ref values[index]);
        }
    
        //Reverse the tail set's order.
        int limit = (values.Length - tail) / 2;
        for (int index = 0; index < limit; index++)
            Swap(ref values[tail + index], ref values[values.Length - 1 - index]);
    
        //If the entire list was in reverse order, tail will be zero.
        return (tail != 0);
    }
    
    private static void Swap(ref T left, ref T right)
    {
        T temp = left;
        left = right;
        right = temp;
    }
    

提交回复
热议问题