在一个列表中搜索数字加起来就是C#中的和

本文关键字:起来 数字 搜索 列表 一个 | 更新日期: 2023-09-27 18:22:05

我让用户输入一组1到19之间的数字……并且需要找到尽可能多的加起来为40的数字,每个数字只能使用一次。

因此,列表是:19、17、11、13、8、9、7、5、10、16、14、8、7、3。

那么输出应该是:
19、11、10
16、14、7、3
17、8、8、7

列表中还有13、9和5。

我找到了一些建议,但它们似乎只寻找一个匹配,我也尝试了一下,但仍然缺乏一些完善。

    private void btnCalc_Click(object sender, RoutedEventArgs e)
    {
        // Copy the list to a new list:
        List<int> lookInto = new List<int>();
        foreach(int i in weaponList)
        {
            lookInto.Add(i);
        }
        int lookFor = 40;
        while (lookFor > 0)
        {
            lookFor = Search(lookInto, lookFor);
        }
        if (lookFor != -1)
        {
            listSell.Items.Add(answer);
        }
    }
    private int Search(List<int> hay, int needle)
    {
        int lowestValue = hay.Min();
        int highestValue = hay.Max();
        if (hay.BinarySearch(needle) > 0)
        {
            int index = hay.BinarySearch(needle);
            if (answer == "")
            {
                answer += hay[index].ToString();
                needle -= hay[index];
                hay.Remove(needle);
            }
            else
            {
                answer += ", " + hay[index].ToString();
                needle -= hay[index];
                hay.Remove(needle);
            }
        }
        if (needle - highestValue > lowestValue || needle - highestValue == 0)
        {
            if (answer == "")
            {
                answer += highestValue.ToString();
                needle -= highestValue;
                hay.Remove(highestValue);
            }
            else
            {
                answer += ", " + highestValue.ToString();
                needle -= highestValue;
                hay.Remove(highestValue);
            }
        }
        else
        {
            for (int i = 0; i > hay.Count; i++)
            {
                if (needle - hay[i] == 0 || needle - hay[i] > lowestValue)
                {
                    if (answer == "")
                    {
                        answer += hay[i].ToString();
                        needle -= hay[i];
                        hay.RemoveAt(i);
                    }
                    else
                    {
                        answer += ", " + hay[i].ToString();
                        needle -= hay[i];
                        hay.RemoveAt(i);
                    }
                }
            }
            if (needle > 0)
            {
                needle = -1;
            }
        }
        return needle;
    }

在一个列表中搜索数字加起来就是C#中的和

我很快就要离开了,无法键入实际的代码块,但您可以这样做:创建一个所有数字的镜像静态数组,使用递归函数逐步完成并尝试将该数组中的数字相加,直到达到40,如果它们超过40,它只会返回-1,否则,所有用于达到40的索引,每次它返回一组索引时,都要从镜像数组中删除这些数字,这样下一次迭代就不会试图使用它们并将这些数字添加到集合列表中。当递归函数停止时,主数组中剩下的是未使用的数字,集合列表将包含所有找到的集合。

我希望这能有所帮助!