Preface
Recently, arranging and combining calculation was used in the project. Although it is relatively simple, the entire learning process still needs to be recorded so that you can learn from experience in the future.
Generally speaking, arrangement and combination are equivalent to search.
Note:
1. Derepeat: Specify that the order of subsets must be ascending;
2. The result processing of candidate arrays. It must be copied deep, otherwise the final result set will be empty (a bunch of pointers added).
3. When writing recursion (DFS: Depth priority search), the idea is to first find out all those starting with 1, and then find out all those starting with 2... All things you did before recursion must be erased back afterwards. What you do recursively can be described clearly in one sentence. Recursion is one thing that is constantly reducing the scale, but it all does.
The method is as follows:
The initial idea was to use factorials to solve the problem of permutation and combination, so I thought of recursion.
long arithmetic(int n) { if (n>1) { return n*arithmetic(n-1); }else if (n == 1){ return 1; }else{ return 1; } }
However, in recursion, there is a disadvantage. When the number reaches a certain level, the value will cross the boundary. Even if the long long type is used, it will still cross the boundary. Therefore, the factorial method is temporarily put on hold.
The second idea that comes to mind is to use the for loop to solve the problem. Only using the algorithm of arrangement, factorials must be used, but in terms of combinations, it can be solved in another way.
The solution is to prevent the numerical value from crossing the boundary. You can make the numerator and the denominator approximately divide, then multiply the next numerator and then calculate the denominator approximately divide. And so on. Without further ado, just upload the code:
/** Double Color Ball Ordinary Choice Bet */ - (long)lotterySSQPTRecursiveWithRedBalls:(NSUInteger)redBalls blueBalls:(NSUInteger)blueBalls{ if (redBalls > 5 && blueBalls > 0) { if (redBalls == 6) { return blueBalls; }else{ NSUInteger count = (redBalls-6 > 6) ? 6 : redBalls-6; long number = 1; long molecular = 1; long denominator = 1; for (int i = 0; i < count; i++) { molecular = molecular*(redBalls-i); denominator = denominator * (i+1); number = (molecular*number)/denominator; molecular = 1; denominator = 1; } number = number*blueBalls; return number; } }else{ return 0; } }
Compared to using factorials directly, I personally think that for loop is better. If you have any better solutions, please leave a message!
Friends who want to see the Demo,Click here to send (Local download)
Summarize
The above is the entire content of this article. I hope that the content of this article has a certain reference value for everyone's study or work. If you have any questions, you can leave a message to communicate. Thank you for your support.