Recursion to get the number of different combinations of n people and k groups

I do recursion using Java and I got into a problem. I am trying to make a method, which I call "groups", that takes the number of people and how many groups there are and returns the number of different combinations that people and groups have. In addition, the ordering of people in groups does not matter, as does the ordering of groups.

The code I have so far is:

public long groups(int n, int k) {
    if(k==1) return 1;
    if(k==n) return 1;
    else return groups(n-1, k) + groups(n-1, k-1);
}

However, it returns incorrect values. The first two lines are basic cases that say that if there is 1 group, then there is only one way to divide people, it makes sense. Another thing is when there are as many people as there are groups, and in this case there is only one way to divide them into one person in each group. The last statement is where I think I am having problems, I think that every time it is a recursive call, one person should be output (n is the number of people, therefore n-1), and this person can use ether join a group (k) or create your own group (k-1).

I just figured out a bit how recursion works and can help a bit.

These are the values ​​I expect:

groups(2,1) = 1
groups(2,2) = 1
groups(3,2) = 3
groups(4,2) = 7
groups(4,3) = 6
groups(5,3) = 25
+3
2

-

... (k)...

, "k",

    public long groups(int n, int k) {
        if(k==1) return 1;
        if(k==n) return 1;
        else return k * groups(n-1, k) + groups(n-1, k-1);
    }

( k)

+4

() - , . , , , , .

.

groups(2,1) = 2
groups(2,2) = 1
groups(3,2) = 3
groups(4,2) = 6
groups(4,3) = 4
groups(5,3) = 10

, , , , , .

( , , , , , , . )

0

Source: https://habr.com/ru/post/1773441/


All Articles