How to type sets for a given string [duplicate]

馋奶兔 提交于 2019-12-02 23:20:46

问题


Possible Duplicate:
How can I obtain all the possible combination of a subset?

I am trying to type the sets for a given string for example "123" will give {1}{2}{3}{13}{23}{12}{123}{} but my code gives me 1 1 Please can Anyone tell me why and please help me to fix it Thanks all

using System;
using System.Collections.Generic;
using System.Linq; 
using System.Text;

namespace TestAAD
{
class Program
{
    static List<string> sets = new List<string>();
    static int len = 0;

    private static void Generte_Sets(string str, int i)
    {

        sets.Add(str[i].ToString());

        if (i < len)
            Generte_Sets(str, i + 1);
        else
        {
            for (int j = 0; j < sets.Count; j++)
                Console.Write(sets[j]);
            Console.WriteLine();
        }

        sets.Remove(str[i].ToString());  
        if (i < len)
            Generte_Sets(str, i + 1);
        else
        {
            for (int j = 0; j < sets.Count; j++)
                Console.Write(sets[j]);
            Console.WriteLine();
        }
    }

    static void Main(string[] args)
    {
        string set = "123";

        Generte_Sets(set, 0);
        len = set.Length;
        for (int i = 0; i < sets.Count; i++)
        {
            Console.WriteLine(sets[i]);
        }
    }
}

}

Please I need help to type the sets I need quick help thanks All


回答1:


class Program
    {
        static List<string> sets = new List<string>();
        static int len = 0;

        private static void Generte_Sets(string str, int i)
        {
            sets.Add(str[i].ToString());           

            **if (i + 1 < len)**
                Generte_Sets(str, i + 1);
            else
            {
                for (int j = 0; j < sets.Count; j++)
                    Console.Write(sets[j]);
                Console.WriteLine();
            }

            sets.Remove(str[i].ToString());          

            **if (i + 1 < len)**
                Generte_Sets(str, i + 1);
            else
            {
                for (int j = 0; j < sets.Count; j++)
                    Console.Write(sets[j]);
                Console.WriteLine();
            }
        }

        static void Main(string[] args)
        {
             string set = "123"; 
             **len = set.Length;**
             Generte_Sets(set, 0);

            for (int i = 0; i < sets.Count; i++)
            {
                Console.WriteLine(sets[i]);
            }
        }
    }


来源:https://stackoverflow.com/questions/13778947/how-to-type-sets-for-a-given-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!