思路:求出所有可能的组合, 判断每个组合相加的值是否等于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();
}
}
}
}
1173


,给定一个M值,要求数组中的一个或多个值相加的和等于M,有多少种组合?&spm=1001.2101.3001.11974&articleId=6609250&d=1&t=3&u=75a2cfd875de42deb4148b8878456756)

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



