List all possible combinations of k integers between 1…n (n choose k)

后端 未结 4 476
萌比男神i
萌比男神i 2021-02-05 21:42

Out of no particular reason I decided to look for an algorithm that produces all possible choices of k integers between 1...n, where the order amongst the k integer doesn\'t mat

4条回答
  •  傲寒
    傲寒 (楼主)
    2021-02-05 22:39

    Asaf,

    You are asking us to evaluate your algorithm, but you don't explain your algorithm -- not even in code comments. So you want everyone to spend an hour or more reverse engineering the algorithm from the code, just so we can understand your question before we answer it?

    Please edit your question to explain your algorithm.

    One thing is obvious -- the memory footprint of your code is horrendous. For even modest values of n, the number of combinatations will easily be in the billions, which will require more memory than most computers have. Plus you are using dynamically grown arrays, which keep reallocating and copying themselves as they grow. Plus your program generates subsets in different arrays and merges them. All in all, your program will require many times the amount of memory that would be ideally needed to store the list, and it will spend most of it's time just copying data back and forth.

    If you must have all the values in an array at once, at least start off by computing the size of the array you need -- n! / (n-k)! / k! -- and then just filling it in.

    Even better would be code that "lazily" just computed each member of the sequence as it was needed. See this question from the related questions sidebar

提交回复
热议问题