/*Backtracking algorithm used in the program:->>Fix a character in the first position and swap the rest of the character with the first character.Like in ABC, in the first iteration three strings are formed: ABC, BAC, and CBA by swapping A withA, B and C respectively.>>Repeat step 1 for the rest of the characters like fixing second character B and so on.>>Now swap again to go back to the previous position. E.g., from ABC, we formed ABC by fixing B again,and we backtrack to the previous position and swap B with C. So, now we got ABC and ACB.>>Repeat these steps for BAC and CBA, to get all the permutations.*/public class PermuteString {//Function for swapping the characters at position I with character at position jpublic static String swapString(String a, int i, int j) {char[] b =a.toCharArray();char ch;ch = b[i];b[i] = b[j];b[j] = ch;return String.valueOf(b);}public static void main(String[] args){String str = "ABC";int len = str.length();System.out.println("All the permutations of the string are: ");generatePermutation(str, 0, len);}//Function for generating different permutations of the stringpublic static void generatePermutation(String str, int start, int end){//Prints the permutationsif (start == end-1)System.out.println(str);else{for (int i = start; i < end; i++){//Swapping the string by fixing a characterstr = swapString(str,start,i);//Recursively calling function generatePermutation() for rest of the charactersgeneratePermutation(str,start+1,end);//Backtracking and swapping the characters again.str = swapString(str,start,i);}}}}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。