本文介绍了使用+和-C#的数字的所有组合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想采用一种递归方法,以使用+/-(例如特定长度)来查找数字的所有可能组合:输入:

I want to make a recursive method to find all the possible combination for a number using +/-, with a specific length for example:For input:

  • 长度:6
  • 数量:3

对于输出:

  • 1 + 2 + 3-5-5 + 6 = 3
  • 1 + 2-3 + 4 + 5-6 = 3
  • 1-2-3-4 + 5 + 6 = 3

您能为我解释一下我该怎么做吗?谢谢.

Can you explain for me how can I do that ?Thanks you.

推荐答案

嗯,假设所有组合"必须从 1 ( 1、2、3,...,n )开始的自然数生成:

Well, assuming that "all combinations" must be generated from consequent natural numbers starting from 1 (1, 2, 3, ..., n) you can implement something like this:

using System.Linq;

...

// Here we generate all possible formulae and their sums:
// 1 - 2 - 3 - 4 - 5 - 6
// 1 - 2 - 3 - 4 - 5 + 6
// 1 - 2 - 3 - 4 + 5 - 6
// 1 - 2 - 3 - 4 + 5 + 6 
// ...
// 1 + 2 + 3 + 4 + 5 + 6
private static IEnumerable<(string formula, int sum)> GenerateRecursive(int number) {
  if (number == 1) 
    yield return ("1", 1);
  else
    foreach (var pair in GenerateRecursive(number - 1)) {
      yield return ($"{pair.formula} - {number}", pair.sum - number);
      yield return ($"{pair.formula} + {number}", pair.sum + number);
    }
}

// Here we query formulae generated for having required sum
private static IEnumerable<string> SolveFor(int target, int count) {
  return GenerateRecursive(count)
    .Where(item => item.sum == target)
    .Select(item => $"{item.formula} = {item.sum}");
}

然后

Console.Write(string.Join(Environment.NewLine, SolveFor(3, 6)));

结果:

1 - 2 - 3 - 4 + 5 + 6 = 3
1 + 2 - 3 + 4 + 5 - 6 = 3
1 + 2 + 3 - 4 - 5 + 6 = 3

这篇关于使用+和-C#的数字的所有组合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-03 01:48