How to implement an efficient permutation and combination algorithm for java version
This article mainly introduces how to achieve an efficient java version of the permutation and combination algorithm, has a certain reference value, interested friends can refer to, I hope you can learn a lot after reading this article, the following let the editor take you to understand it.
The details are as follows
Package BeanUtil;import java.util.ArrayList;import java.util.List;import com.work.core.exception.OurException / * author wangmingjie * @ date 2009-1-1 01:22:19 * / public class Copy_2_of_StatisAnyThree {/ / Combinatorial algorithm / / the idea of this procedure is to open an array whose subscript indicates the number from 1 to m. A value of 1 indicates that the number represented by the subscript / / is selected, while a value of 0 indicates that the number represented by the subscript / / is selected. / / initialize first, setting the first n elements of the array to 1, indicating that the first combination is the first n. / / then scan the "10" combination of the array element values from left to right, find the first "10" combination and change it to / / "01" combination, while moving all the "1s" on its left to the far left end of the array. / / when the first "1" is moved to the position of the mmurn of the array, that is, when all the n "1s" are moved to the rightmost end, there is / / to the last combination. / / for example, the combination of choosing 3 out of 5: / / 11100 / / 1Magi 2mag3 / / 11010 / / 1Mei4 / / 10110 / / 1Min 3Min 4 / / 01110 / / 2Min 3Min 4 / / 11001 / / 1Min 2Min 5 / / 1101l / 1Min 2Jing 5 / / 10101 / 1Min 3Min 5 / 01101l / 2Mol 3 5 / / 1 011 / / 1 public static void main 4 Copy_2_of_StatisAnyThree 5 / 0 10 11 / / 2 Copy_2_of_StatisAnyThree 4 5 / / 0 011 11 / / 3 Magi 4 5 Copy_2_of_StatisAnyThree (Copy_2_of_StatisAnyThree [] args) {new Copy_2_of_StatisAnyThree () S.printAnyThree ();} / * / public void printAnyThree () {int [] num = new int [] {1Power2, 3pint 4, 5Power6}; print (combine (num,3));} / * Select m digits out of n numbers * @ param a * @ param m * @ return * / public List combine (int [] aMint m) {int n = a.length If (m > n) {throw new OurException ("error! There are only "+ n +" elements in array a. " + m + "is greater than" + 2 + "!!");} List result = new ArrayList (); int [] bs = new int [n]; for (int iTuno Tipi)