【问题标题】:How to type sets for a given string [duplicate]如何为给定的字符串键入集合[重复]
【发布时间】:2012-12-08 15:35:22
【问题描述】:

可能重复:
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]);
        }
    }
}

}

我需要帮助来输入集合 我需要快速帮助 谢谢大家

【问题讨论】:

标签: c# list recursion set backtracking


【解决方案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]);
            }
        }
    }

【讨论】:

  • 感谢它完美运行
猜你喜欢
  • 1970-01-01
  • 2017-06-06
  • 2015-01-22
  • 2013-05-23
  • 2017-01-08
  • 2017-03-22
  • 1970-01-01
  • 2020-12-13
  • 1970-01-01
相关资源
最近更新 更多