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

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

    Below is my generics version of the next permutation algorithm in C# closely resembling the STL's next_permutation function (but it doesn't reverse the collection if it is the max possible permutation already, like the C++ version does)

    In theory it should work with any IList<> of IComparables.

        static bool NextPermutation(IList a) where T: IComparable
        {
            if (a.Count < 2) return false;
            var k = a.Count-2;
    
            while (k >= 0 && a[k].CompareTo( a[k+1]) >=0) k--;
            if(k<0)return false;
    
            var l = a.Count - 1;
            while (l > k && a[l].CompareTo(a[k]) <= 0) l--;
    
            var tmp = a[k];
            a[k] = a[l];
            a[l] = tmp;
    
            var i = k + 1;
            var j = a.Count - 1;
            while(i

    And the demo/test code:

            var src = "1234".ToCharArray();
            do
            {
                Console.WriteLine(src);
            } 
            while (NextPermutation(src));
    

提交回复
热议问题