如何使用 C# 找到對應 K 和 K 和的唯一組合?


建立一個輸出列表來儲存有效序列,建立一個當前列表來儲存在遞迴樹路徑中找到的當前序列。一個回溯函式,它將進行遞迴直到實現目標,否則,它應回溯到以前階段,因為目標變為小於 0。在任何時候,如果目標變為 0,然後將候選陣列新增到結果中,因為候選陣列中的值必須加起來等於給定的目標。

如果那些不是這種情況,那麼逐個新增候選陣列中的元素並遞迴前進。

比如,這個數是 5,而 k 是 2,因此我們需要形成大小為 2 的數字組合,形成 5。輸出將是“1,4”、“2,3”。

示例

 即時演示

using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
namespace ConsoleApplication{
   public class BackTracking{
      public void UniqueCombinationSumOfExactKNumbers(int n, int k){
         int[] array = new int[n];
         for (int i = 1; i < n; i++){
            array[i] = i;
         }
         List<int> currentList = new List<int>();
         List<List<int>> output = new List<List<int>>();
         UniqueCombinationSumOfExactKNumbers(array, n, k, 0, 0, currentList, output);
         foreach (var item in output){
            StringBuilder s = new StringBuilder();
            foreach (var item1 in item){
               s.Append(item1.ToString());
            }
            Console.WriteLine(s);
            s = null;
         }
      }
      private void UniqueCombinationSumOfExactKNumbers(int[] array, int target, int countOfNumbers, int sum, int index, List<int> currentList, List<List<int>> output){
         if (sum == target){
            if (currentList.Count == countOfNumbers){
               List<int> newList = new List<int>();
               newList.AddRange(currentList);
               output.Add(newList);
               return;
            }
         }
         else if (sum > target){
            return;
         }
         else if (currentList.Count == countOfNumbers && sum != target){
            return;
         }
         else{
            for (int i = index; i < array.Length; i++){
               currentList.Add(array[i]);
               UniqueCombinationSumOfExactKNumbers(array, target, countOfNumbers, sum + array[i], i + 1, currentList, output);
               currentList.Remove(array[i]);
            }
         }
      }
   }
   class Program{
      static void Main(string[] args){
         BackTracking b = new BackTracking();
         b.UniqueCombinationSumOfExactKNumbers(5, 2);
      }
   }
}

輸出

14
23

更新於:2021 年 8 月 27 日

220 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始
廣告