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

后端 未结 4 487
萌比男神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:26

    Here's a relatively simple/efficient nCr program I wrote a while ago in C:

    main(n,k){float t=0,r=1;for(scanf("%d, %d",&n,&k);t++

    Okay ... readable version. =] (Not sure if this is 1:1 corresponding with the above.)

    void nCr(int n, int k) {
        float curK = 0, r = 1;
        while(curK < k) {
            ++curK;
            printf("%.0f\n", r);
            r *= (1 + n - curK) / curK;
        }
    }
    

    Instead of printing, you could yield or whatever (I don't know C#) into your list.

提交回复
热议问题