简体   繁体   中英

how to find the number of ways of choosing k objects of 3 types

You are given an integer k and 3 types of objects - A, B and C each type has a large supply of objects. In how many ways can u arrange k objects so that you can choose any type of object any number of times with one restriction that B always comes between A and C or C and A.

for example if, k is 3, then the answer is : 10 explanation : {AAA, AAC, ABC, ACA, ACC, CAA, CAC, CBA, CCA, CCC}

I tried to solve it using dynamic programming, I don't know if that's the correct approach, though.

I tried something like this : f(n) = 2*f(n-1) + f(n-2) , where you take an array of size k and f(1) = 2 {A, C} and f(2) = 4 {AA, AC, CA, CC} ,

so if(n-1)th alphabet is A or C, then nth alphabet can A or C, but if it's B, then nth alphabet can only be the complementary aplphabet ie, if (n-2)th letter is A, then nth letter is C or vice versa. But I feel like I'm missing some cases.

Is there a better way, can someone help me with this?

[Edited]

Recursion:

F(1) = 2
F(2) = 4
F(N) = 2 * F(N - 1) + F(N-2)

explanation: any valid combination ends with A or C.
To make n-combination, we can add both A and C to any (n-1)-combination - two variants.
And we have one more variant, adding to (n-2) combinations: BA for xxxxC and BC for xxxxA

Let L be the language of such strings, and La and Lc be the subsets of the language where the strings end with A or C respectively.

Then we can write this unambiguous grammar:

L = La | Lc
La = "A" | L + "A" | Lc + "BA"
Lc = "C" | L + "C" | La + "BC"

Let L(n), La(n), Lc(n) be the number of strings of length n in each of the three languages. By symmetry, La(n) = Lc(n) = L(n)/2.

Then, from the second equation and using the fact that the grammar is unambiguous, for n > 1, La(n) = L(n-1) + Lc(n-2), and substituting we get: L(n) = 2L(n-1) + L(n-2). We have L(0)=0 and L(1)=2.

To compute L, we can write iterative code (which you might call dynamic programming):

def L(n):
    a, b = 0, 2
    for _ in xrange(n):
        a, b = b, a + 2 * b
    return a

Or, like we do for the Fibonacci series, we can solve it using matrix exponentiation, which can be done in O(log n) arithmetic operations.

L(n) = the first component of [0 1]^n (0)
                              [1 2]   (2)

This is a generalised solution. Say you have n number of objects and you have to choose k objects out of them. You can choose x1,x2,x3.. objects from each type. And their sum

x1+x2+x3...+xn=k 0<=xi

Hence, provided you can select each object or not ( 0<=xi ), the answer will be (k+n-1)C(n-1)

This is a simple solution of an integral equation

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM