A variant of the Fibonacci sequence interview questions

Question: There is a pile of N balls. Only one or two balls can be taken from the pile at a time. How many ways are there in total to take the balls.

Let's take an example to illustrate the problem. For example, there are 3 balls in the ball pile, so there are three ways to take them:
  • 1,1,1
  • 1,2
  • 2,1


At first glance, it has nothing to do with Fibonacci. At that time, this question was directly regarded as a high school permutation combination-. -' After being reminded, the taste came back.

Solution 1: Recursive method.

The essence of the sensory algorithm is that. . . . You have to experience this kind of algorithm. After all, if you don’t have training/experience, I think it’s difficult to directly position your thinking on the correct track. I heard that those who engage in ACM have undergone a lot of training, just like before the college entrance examination. There is a reason to do the paper.

Then back to the topic, the method F(N) of taking N balls can actually be divided into the following two cases

. The first case is that the last time (the one that’s gone after taking it) only took one ball, then in fact This method is exactly F(N-1), that is, the method of taking N-1 balls.
The second case is when two balls are taken for the last time. Then this method is F(N-2).

Conclusion: F(N)=F(N-1)+F(N-2) can be obtained, which is the Fibonacci sequence. The end condition of the recursion is to return 0 when N is 0, return 1 when N is 1, and return 2 when N is 2 (1, 1; 2 two options).

Solution 2: permutation and combination.

Precisely because high school has done many such problems, first of all, I used this kind of thinking to solve the problem. The solution is as follows:
first replace N with a real number, which is easy to understand, such as N=6.

Then, in the most extreme two cases, either take 1 every time, or take 2 every time, so there is only one kind of method.
1,1,1,1,1,1
2,2,2 Next, you can use the exhaustive method to imagine the process

of taking 2 balls each time from 0 to the maximum number of times.
1 time 2, then 1 must be taken 4 times; the problem becomes, now there are 4 1s, 1 2, how many ways are there, the result is C5, 4==C5, 1==5
in all the processes If you take 2 twice, then you must take 1 twice; the problem becomes, now there are 2 2s and 2 1s, what are the ways to take them, the result is C4, 2==6

∴ (the character on the left is awesome) The final result is that 1+1+5+6=13

can be deduced from N=6 to all cases, in fact, the process of taking 2 from 0 to the maximum number of 2 , the cumulative sum of permutations and combinations can be obtained by looping.


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326490573&siteId=291194637