Recursion and permutations
Let's say that we have two boxes of pencil开发者_如何学Cs (in first box just blue and in second just red pencils). So the question now is, in how many ways can we put x red and y blue pencils in the line?
Example: we have 3 Red pencils, and 1 Blue. Then we have 4 different ways. Combinations: BRRR, RBRR, RRBR, RRRB.
So with 10 Red and 10 Blue pencils we have 184756 different ways of putting them in line. So guys, how to write this in a recursive way?
Thank you very much for your help.
This sounds like homework, so here are some hints:
When dealing with recursion, you need to think about the base case. Here this base case is 0 pencils. How many ways can you order 0 pencils?
Ok, now the recursive cases: how many ways can you order a non-zero amount of pencils? If you have any red pencils then you can start with a red pencil, followed by the rest of the pencils. If you have any blue pencils then you can start with a blue pencil, followed by the rest of the pencils.
Think binary tree, depth = # of pencils in the line.
The root is zero pencils. Level 1 had one blue pencil and one red pencil. Level 2....you see the pattern.
there is no need to do it in recursion form since it can be calculated using (x+y)!/(x!y!)
but if u're insistent u can use something like this: C(x,y)=C(x-1,y)+C(x,y-1)
with base cases: C(z,0)=C(0,z)=1
that z is any natural number
精彩评论