Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C#

วิธีหาสับเซตที่แตกต่างกันจากอาร์เรย์ที่กำหนดโดยใช้ Backtracking ด้วย C#


ปัญหาสับเซตที่แตกต่างกันให้เราได้การจัดหมู่ที่ต่างกันจากอาร์เรย์ที่กำหนด

เมื่อเป้าหมายคือ 2 จากอาร์เรย์ เราจะเอาการจัดหมู่ทั้งหมดที่สอดคล้องกับตัวเลข 2 เมื่อเป้าหมายคือ 3 จากอาร์เรย์ เราจะเอาการจัดหมู่ทั้งหมดที่สอดคล้องกับจำนวน 3 ในตัวอย่างด้านล่าง อาร์เรย์คือ [1,2,3] และเป้าหมายคือ 2 ดังนั้นเราจะเอาการจัดหมู่ทั้งหมดที่สอดคล้องกับตัวเลข 2 คือ "1,2", "2,3", "1,3"

ตัวอย่าง

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

namespace ConsoleApplication
{
    public class BackTracking
    {
        public void Subsets(int[] array)
        {
            List currentList = new List();
            List results = new List();
            BackTrackkingCombination(array, 2, 0, currentList, results);
            foreach (var item in results)
            {
                StringBuilder s = new StringBuilder();
                foreach (var item1 in item)
                {
                    s.Append(item1.ToString());
                }
                Console.WriteLine(s);
                s = null;
            }
        }

        public void BackTrackkingCombination(int[] array, int size, int startIndex, List currentList, List results)
        {
            if (currentList.Count == size)
            {
                StringBuilder s = new StringBuilder();
                foreach (var item in currentList)
                {
                    s.Append(item);
                }
                results.Add(s.ToString());
                return;
            }
            for (int i = startIndex; i < array.Length; i++)
            {
                currentList.Add(array[i]);
                BackTrackkingCombination(array, size, i + 1, currentList, results);
                currentList.Remove(array[i]);
            }
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            BackTracking b = new BackTracking();
            int[] arrs = { 1, 2, 3 };
            b.Subsets(arrs);
        }
    }
}

ผลลัพธ์

12 13 23