单词全排列
对一个包含n个字母的单词进行全排列:
1,对该单词右边n-1个字母进行全排列
2,轮换所有字母(所有字母左移一位,最左边的字母移动至最右边)
3,以上步骤重复n次(以保证该单词的所有字母都曾经处于第一位)
public class FullPermutation { private char[] chars; private int length; public FullPermutation(String str){ chars = str.toCharArray(); length = chars.length; } public void permutation(int num){ if(num == 1) return; for(int i = 0 ; i < num ; i++){ permutation(num - 1); if(num == 2){ System.out.println(String.valueOf(chars)); } move(num); } } private void move(int num){ int n = length - num; char temp = chars[n]; int i = n + 1; for( ; i < length ; i++){ chars[i-1] = chars[i]; } chars[i-1] = temp; } public static void main(String[] args) { String str = "abc"; FullPermutation fp = new FullPermutation(str); fp.permutation(str.toCharArray().length); } }
abc acb bca bac cab cba