如何在 C# 中使用回溯法从给定数组中找到目标和?


目标和问题是找到这样的一个子集,这个子集的元素的和等于给定的数。最差情况下回溯法生成了所有排列,但通常情况下,它在解决子集和问题时比递归法效果要好。

如果有 n 个正整数子集 A 和一个值 sum,找出给定集合中是否存在这样的一个子集,其元素的和等于给定的值 sum

假设我们有一个数组 [1,2,3] 输出将是 “1,1,1,1 “, “1,1,2”,”2,2”,”13” 根据输出,“31 ”、“211” 、“121” 可以被丢弃

示例

 动态演示

using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
namespace ConsoleApplication{
   public class BackTracking{
      public void Combinationsums(int[] array, int target){
         List<int> currentList = new List<int>();
         List<List<int>> results = new List<List<int>>();
         int sum = 0;
         int index = 0;
         CombinationSum(array, target, currentList, results, sum, index);

         foreach (var item in results){
            StringBuilder s = new StringBuilder();
            foreach (var item1 in item){
               s.Append(item1.ToString());
            }
            Console.WriteLine(s);
            s = null;
         }
      }
      private void CombinationSum(int[] array, int target, List<int> currentList, List<List<int>> results, int sum, int index){
         if (sum > target){
            return;
         }
         else if (sum == target){
            if (!results.Contains(currentList)){
               List<int> newList = new List<int>();
               newList.AddRange(currentList);
               results.Add(newList);
               return;
            }
         }
         else{
            for (int i = 0; i < array.Length; i++){
               currentList.Add(array[i]);
               CombinationSum(array, target, currentList, results, sum + array[i], i);
               currentList.Remove(array[i]);
            }
         }
      }
   }
   class Program{
      static void Main(string[] args){
         BackTracking b = new BackTracking();
         int[] arrs = { 1, 2, 3 };
         b.Combinationsums(arrs, 4);
      }
   }
}

输出

1111
112
13
22

更新于: 2021 年 8 月 27 日

479 次浏览

启动您的 事业

完成课程认证

开始
广告
© . All rights reserved.