您的位置:首页 > 其它

有一个整数数组(包括正数 负数 和0),给定一个M值,要求数组中的一个或多个值相加的和等于M,有多少种组合?

2011-07-15 17:28 405 查看
思路:求出所有可能的组合, 判断每个组合相加的值是否等于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();
}
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  string
相关文章推荐