Find elements in a list that, together add up to a target number

前端 未结 4 636
没有蜡笔的小新
没有蜡笔的小新 2021-01-07 11:03

Suppose I have a list:

List _arr = new List {1, 3, 4};

And a target of 4

I want to return

4条回答
  •  难免孤独
    2021-01-07 11:06

    If you are after a really good and fast solution to this problem you are not alone.

    This is a well know SUBSET SUM problem. I suggest you could look it up at Wikipedia here:

    http://en.wikipedia.org/wiki/Subset_sum_problem

    Of course you could iterate through all possible subsets looking for your sum but be aware that there is (2 ^ CountOfListElements) possible combinations. If the list is always small in size you will have no problems coding it. Even exponential time solution will work for small sets.

提交回复
热议问题