如何使用 C# 通过回溯从给定数组中找到目标和?
csharpserver side programmingprogramming更新于 2025/4/17 4:52:17
目标和问题是找到一个子集的问题,使得元素和等于给定数字。回溯方法在最坏情况下会生成所有排列,但一般来说,对于子集和问题,其表现优于递归方法。
给定 n 个正整数的子集 A 和一个值和,查找给定集合中是否存在任何子集,其元素和等于给定的和值
假设我们有一个数组 [1,2,3],输出将是 “1,1,1,1 “, “1,1,2”,”2,2”,”13” From the output “31 ”,”211” ,”121” can be discarded
示例
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

