Listing all permutations of a string/integer

后端 未结 29 1981
没有蜡笔的小新
没有蜡笔的小新 2020-11-22 00:44

A common task in programming interviews (not from my experience of interviews though) is to take a string or an integer and list every possible permutation.

Is there

29条回答
  •  盖世英雄少女心
    2020-11-22 01:26

    Slightly modified version in C# that yields needed permutations in an array of ANY type.

        // USAGE: create an array of any type, and call Permutations()
        var vals = new[] {"a", "bb", "ccc"};
        foreach (var v in Permutations(vals))
            Console.WriteLine(string.Join(",", v)); // Print values separated by comma
    
    
    public static IEnumerable Permutations(T[] values, int fromInd = 0)
    {
        if (fromInd + 1 == values.Length)
            yield return values;
        else
        {
            foreach (var v in Permutations(values, fromInd + 1))
                yield return v;
    
            for (var i = fromInd + 1; i < values.Length; i++)
            {
                SwapValues(values, fromInd, i);
                foreach (var v in Permutations(values, fromInd + 1))
                    yield return v;
                SwapValues(values, fromInd, i);
            }
        }
    }
    
    private static void SwapValues(T[] values, int pos1, int pos2)
    {
        if (pos1 != pos2)
        {
            T tmp = values[pos1];
            values[pos1] = values[pos2];
            values[pos2] = tmp;
        }
    }
    

提交回复
热议问题