What technique do I use for when I want to check all possible combinations of a set?

后端 未结 9 2228
既然无缘
既然无缘 2021-01-18 23:38

I\'m working through an interview question that goes like:

Given an array of integers and sum, check whether any combination adds up to the sum.

9条回答
  •  醉酒成梦
    2021-01-19 00:12

    Recursively. Pseudo-code would be something like this:

    function f(set,currentelement,selectedelements,sum,wantedsum)
    {
    for (thiselement=currentelement+1 to lastelement)
       {
       if (sum+thiselement==wantedsum) print out selectedelements+thiselement;
       if (sum+thiselement

提交回复
热议问题