Generating power set recursively without any loops

前端 未结 8 1260
执笔经年
执笔经年 2020-12-16 18:50

How do you write a recursive method PowerSet(String input) that prints out all possible combinations of a string that is passed to it?

For example: PowerSet(\"abc\")

8条回答
  •  遥遥无期
    2020-12-16 19:04

    Based on the info here, here is solution in C#.

    NOTE: the loop in the main function is just to print the result into the console value. No loops used in the PowerSet method.

        public static void Main(string[] args)
        {
    
            string input = "abbcdd";
    
    
            Dictionary < string, string> resultSet = new Dictionary();
    
            PowerSet(input, "", 0, resultSet);
    
            //apply sorting 
            var resultSorted = resultSet.OrderBy(l => l.Key.Length).ThenBy(l=>l.Key);
    
            //print values
            foreach(var keyValue in resultSorted)
            {
                Console.Write("{{{0}}}, ",keyValue.Key);
            }
    
    
        }
    
        /// 
        /// Computes the powerset of a string recursively
        /// based on the Algorithm http://www.ideserve.co.in/learn/generate-all-subsets-of-a-set-recursion
        /// 
        /// Original input string
        /// Temporary variable to store the current char for the curr call
        /// The character position we are evaluating to add to the set
        /// A hash list to store the result
        public static void PowerSet(string input, string temp, int depth, Dictionary resultSet)
        {
    
            //base case
            if(input.Length == depth)
            {
                //remove duplicate characters
                string key = new string(temp.ToCharArray().Distinct().ToArray());
    
                //if the character/combination is already in the result, skip it
                if (!resultSet.ContainsKey(key))
                    resultSet.Add(key, key);
    
                return;//exit 
            }
    
            //left
            PowerSet(input, temp, depth + 1, resultSet);
    
            //right
            PowerSet(input, temp + input[depth], depth + 1, resultSet);
    
        }
    

提交回复
热议问题