Example of Java algorithm for solving full permutation problem based on recursion

  • 2020-11-18 06:11:06
  • OfStack

An example of Java is presented in this paper to solve the permutation problem recursively. To share for your reference, the details are as follows:

Permutation problem

Set R = {r1, r2,... ,rn} is the n elements to be arranged, Ri=R-{ri}. The full arrangement of the elements in the set x is denoted as Perm(X). (ri)Perm(X) represents the arrangement obtained by prefixing ri to each permutation of the full arrangement Perm(X). The full arrangement of R can be summarized as follows:

When n=1, Perm(R)=(r), where r is the only element in the set;

When n > At 1 o 'clock, Perm(R) consisted of (r1)Perm(R1),(r2)Perm(R2),(r3)Perm(R3)... (rn) Perm (Rn).


public class AllSort {
  public static void perm(int[] list, int k, int m) {
    if( k == m) {
      for (int i = 0; i <=m; i++) {
        System.out.print(list[i]);
      }
      System.out.println();
    }
    else{
      for(int i = k; i <= m; i++) {
        swap(list,k,i);
        perm(list, k+1 , m);
        swap(list,k,i);
      }
    }
  }
  public static void swap(int[] list, int a, int b) {
    int temp;
    temp = list[a];
    list[a] = list[b];
    list[b] = temp;
  }
  public static void main(String args[]) {
    int[] list = new int[5];
    for(int i = 0; i < list.length; i++) {
      list[i] = i+1;
    }
    perm(list,0,list.length-1);
  }
}

Operation results:


12345
12354
12435
12453
12543
12534
13245
13254
13425
13452
13542
13524
14325
14352
14235
14253
14523
14532
15342
15324
15432
15423
15243
15234
21345
21354
21435
21453
21543
21534
23145
23154
23415
23451
23541
23514
24315
24351
24135
24153
24513
24531
25341
25314
25431
25413
25143
25134
32145
32154
32415
32451
32541
32514
31245
31254
31425
31452
31542
31524
34125
34152
34215
34251
34521
34512
35142
35124
35412
35421
35241
35214
42315
42351
42135
42153
42513
42531
43215
43251
43125
43152
43512
43521
41325
41352
41235
41253
41523
41532
45312
45321
45132
45123
45213
45231
52341
52314
52431
52413
52143
52134
53241
53214
53421
53412
53142
53124
54321
54312
54231
54213
54123
54132
51342
51324
51432
51423
51243
51234

For more information about java algorithm, please refer to Java Data Structure and Algorithm Tutorial, Java Operation of DOM Node Skills Summary, Java File and Directory Operation Skills Summary and Java Cache Operation Skills Summary.

I hope this article is helpful for java programming.


Related articles: