(Easy) BackTracking Permutations- Algorithm
Posted codingyangmao
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了(Easy) BackTracking Permutations- Algorithm相关的知识,希望对你有一定的参考价值。
Description:
A permutation, also called an “arrangement number” or “order,” is a rearrangement of the elements of an ordered list S into a one-to-one correspondence with S itself. A string of length n has n! permutation.
Source: Mathword(http://mathworld.wolfram.com/Permutation.html)
Below are the permutations of string ABC.
ABC ACB BAC BCA CBA CAB
Here is a solution that is used as a basis in backtracking.
Solution:
class Main public static void main(String[] args) String str = "ABC"; Main m = new Main(); m.Permute(str,0,str.length()-1); public void Permute(String str, int i, int j ) if(i==j) System.out.println(str); else for(int l = i; l<=j; l++) str = swap(str,i,l); Permute(str, i+1, j); str = swap(str,l,i); public String swap(String a, int i, int j) char temp; char[] charArray = a.toCharArray(); temp = charArray[i] ; charArray[i] = charArray[j]; charArray[j] = temp; return String.valueOf(charArray);
以上是关于(Easy) BackTracking Permutations- Algorithm的主要内容,如果未能解决你的问题,请参考以下文章