1,问题描述:在下面的算式中,添加“+”、“-”,“*”,“/”,4个运算符,使得这个式子成立。
5 5 5 5 5=5,不用枚举算法解决,用别的算法解决,求代码

C++程序设计的算法解决问题
- 写回答
- 好问题 0 提建议
- 关注问题
- 邀请回答
-
2条回答 默认 最新
- threenewbee 2019-05-06 11:10关注
递归解决
using System; using System.Linq; using System.Collections.Generic; using System.Text.RegularExpressions; namespace Q760027 { class Program { static IEnumerable<string> solve(string s, int[] v, int t) { if (v.Length == 2) { if (v[0] + v[1] == t) yield return s + "+"; if (v[0] - v[1] == t) yield return s + "-"; if (v[0] * v[1] == t) yield return s + "*"; if (v[1] != 0 && v[0] % v[1] == 0) { if (v[0] / v[1] == t) yield return s + "/"; } yield break; } foreach (var item in solve(s + "+", new int[] { v[0] + v[1] }.Concat(v.Skip(2)).ToArray(), t)) yield return item; foreach (var item in solve(s + "-", new int[] { v[0] - v[1] }.Concat(v.Skip(2)).ToArray(), t)) yield return item; foreach (var item in solve(s + "*", new int[] { v[0] * v[1] }.Concat(v.Skip(2)).ToArray(), t)) yield return item; if (v[1] != 0 && v[0] % v[1] == 0) { foreach (var item in solve(s + "/", new int[] { v[0] / v[1] }.Concat(v.Skip(2)).ToArray(), t)) yield return item; } } static void Main(string[] args) { foreach (string s in solve("", new int[] { 5, 5, 5, 5, 5 }, 5).Where(x => !Regex.IsMatch(x, @"[\+\-][\*\/]"))) Console.WriteLine(s); } } }
++-- +-+- +--+ -++- -+-+ --++ **// */+- */-+ */*/ *//* /*+- /*-+ /**/ /*/* C:\Program Files\dotnet\dotnet.exe (process 5732) exited with code 0. Press any key to close this window . . .
本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 无用评论 打赏 举报