2018 9th Blue Bridge Cup Java Programming Undergraduate Group B Finals Full Arrangement (fill in the blanks)

2018 Ninth Blue Bridge Cup Java Programming Undergraduate Group B Final Individual Problem Solution Summary:

https://blog.csdn.net/daixinliangwyx/article/details/90258768

 

Question 3

Title: Full Arrangement

For a certain string, such as: "1234", find all its permutations.
And it is required that these full arrangements must be arranged in ascending alphabetical order. For " 1234
", it should output (total 4!=24 lines) :
1234
1243
1324
1342
1423
1432
2134
2143
2314
2341
2413
2431
3124
3142
3214
3241
31412
3421
4123
4131 24
4213


The following is the implementation program, please analyze the program logic carefully and fill in the missing code in the underlined part.

// 轮换前k个,再递归处理
import java.util.*;
public class A
{     static void permu(char[] data, int cur){         if(cur==data.length-1){             System.out.println(new String(data));             return;         }         for(int i=cur; i<data.length; i++){             char tmp = data[i];              for(int j=i-1; j>=cur; j--) data[j+1] = data[j];             data[cur] = tmp;            





        



            permu(data, cur+1);            

            tmp = data[cur]; 
            __________________________________________ ;
            data[i] = tmp;            
        }
    }
    
    static void permu(String x){         permu(x.toCharArray(),0);     }     public static void main(String[] args){         permu("1234");     } }


    




Please note: Only fill in the missing content in the underlined part, do not copy existing codes or symbols.


Solution: The problem is very simple as long as you understand the realization idea of ​​full permutation. Before the next permu recursion, move the character in position i to the cur position, and move all the characters in the original [cur, i) segment back one place. , then after the recursive backtracking of permu, restore the previously modified data array, that is, move the characters in the cur position back to the i position, and move all the characters in the (cur, i) segment forward one place, which is the restoration, Filling in the blanks is a for loop that moves the (cur, i] character forward by one.

答案:for (int j = cur; j < i; j++) data[j] = data[j+1]

Guess you like

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