What's time complexity of this algorithm for finding all combinations?

后端 未结 4 1577
梦如初夏
梦如初夏 2020-12-09 03:51

Combinations
Given two integers n and k, return all possible combinations of k numbers out of 1 ... n.
For example

相关标签:
4条回答
  • 2020-12-09 04:29

    Since you are using lists, push_back and pop_back are O(1) operations. Also, you end up generating a valid combination exactly once. Thus, the complexity is O(n choose k).

    0 讨论(0)
  • 2020-12-09 04:30

    I don't think it is O(n^k). Because think about it. Let's assume n=100 and k=2. According to your complexity it will 100 to the power 2. But if it is n=100 and k=10, it will be 100 to the power of 10. But if you think about it, there are far more combinations with n=100,k=2 than n=100,k=10. The complexity is actually is the actual formula: which is n!/(k!(n-k)!). And the complexity therefore will be O(n!/k!(n-k)!).

    0 讨论(0)
  • 2020-12-09 04:49

    The complexity is O(C(n,k)) which is O(n choose k).

    This ends up being equivalent to O(min(n^k, n^(n-k))).

    0 讨论(0)
  • 2020-12-09 04:51

    The time complexity is equal to the number of combinations there are.

    In this case it is n choose k.

    0 讨论(0)
提交回复
热议问题