如何在 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
廣告
資料結構
網路
關係型資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C 語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP