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

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

    One handy insight is to realize that the binary representation of all numbers from 0 to (2^N)-1 is actually a set of bit masks for the possible combinations out of N distinct items. For instance, for N=3 (3 items) and thus (2^3)-1 = 7:

    0: 000 = none
    1: 001 = third item
    2: 010 = second item
    3: 011 = second and third items
    4: 100 = first item
    5: 101 = first and third items
    6: 110 = first and second items
    7: 111 = all 3 items
    

    This makes it very easy to loop through all possible selections in a set order (so that it's impossible to skip or double-visit any potential selection).

提交回复
热议问题