小编Dav*_*ter的帖子

如何使用 LINQ 找到 ±1 ± 2 ± 3 ± ... ± n = k 形式的所有可能组合?

我很难想出一个在 C# 中使用 LINQ 的简单解决方案来解决这个问题:

对于两个给定的数字 n 和 k,找出形式为 ±1 ± 2 ± 3 ± ... ± n = k 的所有可能组合。

例如,对于 n = 5 和 k = 3,结果将是 "-1+2+3+4-5 = 3", "-1+2+3+4-5 = 3"

public static void Main()
{
    int firstNNumbers = Convert.ToInt32(Console.ReadLine());
    int numberOfOperations = firstNNumbers - 1;
    int targetSum = Convert.ToInt32(Console.ReadLine());
    char[] set = { '+', '-' };
    bool hasSolution = false;
    GetAllOperatorCombinations(set, numberOfOperations, targetSum, ref hasSolution);
    if (hasSolution)
    {
        return;
    }
    Console.WriteLine("N/A");
}
public static int …
Run Code Online (Sandbox Code Playgroud)

c# linq

0
推荐指数
1
解决办法
123
查看次数

标签 统计

c# ×1

linq ×1