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

后端 未结 9 2223
既然无缘
既然无缘 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:02

    That sounds like a classic recursion problem. You start with the first element and consider the rest of the array; for each element, either it is picked or it isn't. The base case is when the start index is greater than the length of the array. Something like

    public static bool canSum(int start, int[] array, int sum)
    {
          if (start >= array.Length)
               return sum == 0;
          return canSum(start + 1, array, sum - array[start]) || canSum(start + 1, array, sum);
    }
    

提交回复
热议问题