Find all subsets of length k in an array

前端 未结 13 1933
梦谈多话
梦谈多话 2020-11-27 05:34

Given a set {1,2,3,4,5...n} of n elements, we need to find all subsets of length k .

For example, if n = 4 and k = 2, the output would be

13条回答
  •  一向
    一向 (楼主)
    2020-11-27 05:49

    Slight improvement for @amit top voted answer:

    His code keep checking combinations even when there won't be any chance for them to reach the wanted length. We can stop creating combinations much earlier:

    e.g. for [1,2,3,4,5,6,7,8,9,10] , length = 8 , the code will still try all combinations of length 7,6,5,4,3,2,1 although they will obviously just be thrown away, halting only when idx reaches the end of the list.

    We can improve the running time by stopping earlier, when we already know the set we build + the optional remaining digits will still be too short.

    change :

    //unsuccessful stop clause
    if (idx == superSet.size()) return;
    
    

    into:

    // unsuccessful stop clause
    Integer maxFutureElements = superSet.size() - idx;
    if (current.size() + maxFutureElements < length) return;
    

提交回复
热议问题