与えられた数C#から合計のユニークな組み合わせを見つける方法は?
有効なシーケンスを格納する出力リストを作成し、再帰ツリーのパスで見つかった現在のシーケンスを格納する現在のリストを作成します。ターゲットが達成されるまで再帰に入るバックトラック関数。それ以外の場合は、ターゲットが0未満になると、前のフェーズにバックトラックする必要があります。任意の時点で、ターゲットが0になった場合は、候補配列を結果に次のように追加します。候補配列の値は、指定されたターゲットまで合計する必要があります。
そうでない場合は、候補配列に要素を1つずつ追加し、再帰的に前進します。
たとえば、数値が5であるため、5を形成する数値を見つける必要があります。出力は「1,4」、「2,3」、5になります。出力から014、.023および05を破棄できます
例
using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
namespace ConsoleApplication{
public class BackTracking{
public void UniqueCombinationOfNumbersCorrespondsToSum(int n){
int[] array = new int[n + 1];
for (int i = 1; i <= n; i++){
array[i] = i;}
List<int> currentList = new List<int>();
List<List<int>> output = new List<List<int>>();
UniqueCombinationSum(array, n, 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 UniqueCombinationSum(int[] array, int target, int sum, int index, List<int> currentList, List<List<int>> output){
if (sum == target){
List<int> newList = new List<int>();
newList.AddRange(currentList);
output.Add(newList);
return;
}
else if (sum > target){
return;
}
else{
for (int i = index; i < array.Length; i++){
currentList.Add(array[i]);
UniqueCombinationSum(array, target, sum + array[i], i + 1, currentList, output);
currentList.Remove(array[i]);
}
}
}
}
class Program{
static void Main(string[] args){
BackTracking b = new BackTracking();
b.UniqueCombinationOfNumbersCorrespondsToSum(5);
}
}
}
} 出力
14 23 05
-
Pythonを使用して特定の数値の桁数を見つける方法は?
このプログラムでは、ユーザーが指定した整数の桁数を見つける必要があります。 例 ユーザー入力:123、出力:3 ユーザー入力:1987、出力:4 アルゴリズム Step 1: Take Integer value as input value from the userStep 2: Divide the number by 10 and convert the quotient into Integer typeStep 3: If quotient is not 0, update count of digit by 1Step 4: If quotient is 0, stop
-
C++で指定された依存関係からタスクの順序を見つけます
n個の異なるタスクがあるとします。これらのタスクには、0からn-1までのラベルが付けられています。一部のタスクには前提条件のタスクがある場合があるため、例として、タスク2を選択する場合は、最初にタスク1を終了する必要があります。これはペアとして表されます-[2、1]タスクの総数とリストがある場合前提条件のペアのうち、すべてのタスクを完了するには、タスクの順序を見つける必要があります。正しい注文が複数ある場合は、そのうちの1つを返品できます。また、指定されたすべてのタスクを完了することが不可能な場合は、空の配列を返します。 したがって、入力がn =4で、A =[[1、0]、[2、0]、[3、2