Creating a power set of a Sequence

后端 未结 4 1545
南旧
南旧 2020-12-01 06:49

I am trying to create a program that is a base for creating possible combinations of a sequence, string or a number. This is some sort of encryption / decryption program. I

4条回答
  •  青春惊慌失措
    2020-12-01 07:43

    Very late to the game, but why not the approach below? It seems significantly simpler than the suggestions posted here:

        /*
        Description for a sample set {1, 2, 2, 3}:
        Step 1 - Start with {}:
        {}
        Step 2 - "Expand" previous set by adding 1:
        {}
        ---
        {1}
        Step 3 - Expand previous set by adding the first 2:
        {}
        {1}
        ---
        {2}
        {1,2}
        Step 4 - Expand previous set by adding the second 2:
        {}
        {1}
        {2}
        {1,2}
        ---
        {2}
        {1,2}
        {2,2}
        {1,2,2}
        Step 5 - Expand previous set by adding 3:
        {}
        {1}
        {2}
        {1,2}
        {2}
        {1,2}
        {2,2}
        {1,2,2}
        ---
        {3}
        {1,3}
        {2,3}
        {1,2,3}
        {2,3}
        {1,2,3}
        {2,2,3}
        {1,2,2,3}
        Total elements = 16 (i.e. 2^4), as expected.
        */
    
        private static void PowerSet(IList nums, ref IList> output)
        {
            // ToDo: validate args
            output.Add(new List());
            ExpandSet(nums, 0, ref output);
        }
    
        private static void ExpandSet(IList nums, int pos, ref IList> output)
        {
            if (pos == nums.Count)
            {
                return;
            }
    
            List tmp;
            int item = nums[pos];
    
            for (int i = 0, n = output.Count; i < n; i++)
            {
                tmp = new List();
                tmp.AddRange(output[i]);
                tmp.Add(item);
                output.Add(tmp);
            }
    
            ExpandSet(nums, pos + 1, ref output);
        }
    

提交回复
热议问题