如何为给定字符串键入集合

时间:2012-12-08 15:35:22

标签: c# list recursion set backtracking

  

可能重复:
  How can I obtain all the possible combination of a subset?

我正在尝试为给定字符串键入集合 “123”将提供{1} {2} {3} {13} {23} {12} {123} {} 但我的代码给了我1 1 请任何人可以告诉我为什么,请帮助我解决它 谢谢大家

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]);
        }
    }
}

}

我需要帮助才能输入套装 我需要快速帮助 谢谢所有

1 个答案:

答案 0 :(得分:0)

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]);
            }
        }
    }