Listing all permutations of a string/integer

后端 未结 29 1973
没有蜡笔的小新
没有蜡笔的小新 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:30

    Here is the function which will print all permutations recursively.

    public void Permutations(string input, StringBuilder sb)
        {
            if (sb.Length == input.Length)
            {
                Console.WriteLine(sb.ToString());
                return;
            }
    
            char[] inChar = input.ToCharArray();
    
            for (int i = 0; i < input.Length; i++)
            {
                if (!sb.ToString().Contains(inChar[i]))
                {
                    sb.Append(inChar[i]);
                    Permutations(input, sb);    
                    RemoveChar(sb, inChar[i]);
                }
            }
        }
    
    private bool RemoveChar(StringBuilder input, char toRemove)
        {
            int index = input.ToString().IndexOf(toRemove);
            if (index >= 0)
            {
                input.Remove(index, 1);
                return true;
            }
            return false;
        }
    

提交回复
热议问题