思路:求出所有可能的组合, 判断每个组合相加的值是否等于M;计数组长度为N,则每一种组合相当于一个长度为N的二进制串:串中每一位表示对应整数是否在此组合中,1表示在,0表示不在;如 01101...表示这个组合不包含数组的 0和3,但包含 1,2,4.
class Test
{
static void Main(string[] args)
{
int[] a = { 0, 1, -1, 3, 5, 9, 1, 2, 4, 7 };
int m = 6;
int tempVal = 0;
var tempRet = new List<int>();
for (int i = 0; i < (1 << a.Length); i++)
{
tempVal = 0;
tempRet.Clear();
for (int j = 0; j < a.Length; j++)
{
if (((1 << j) & i) != 0)
{
tempVal += a[j];
tempRet.Add(a[j]);
}
}
if (tempVal == m)
{
foreach (var t in tempRet)
{
Console.Write(t + " ");
}
Console.WriteLine();
}
}
}
}
本文介绍了一种通过二进制表示法解决数组中元素组合求和等于特定值M的问题,通过枚举所有可能的组合并计算其和来找到符合条件的组合。
,给定一个M值,要求数组中的一个或多个值相加的和等于M,有多少种组合?&spm=1001.2101.3001.5002&articleId=6609250&d=1&t=3&u=7eaa5befba36407e81349a730a2d201b)
6994

被折叠的 条评论
为什么被折叠?



