27、字符串的排列

一、题目

输入一个字符串,按字典序打印出该字符串中字符的所有排列。例如输入字符串abc,则打印出由字符a,b,c所能排列出来的所有字符串abc,acb,bac,bca,cab和cba。

输入一个字符串,长度不超过9(可能有字符重复),字符只包括大小写字母。

二、解法

基于回溯法:

 1 import java.util.ArrayList;
 2 import java.util.Collections;
 3 public class Solution {
 4     public ArrayList<String> Permutation(String str) {
 5         ArrayList<String> res = new ArrayList<String>();
 6            if(str != null && str.length() > 0){
 7                PermutationHelper(str.toCharArray(),0,res);
 8                Collections.sort(res);
 9            }
10            return res;
11     }
12     //递归实现
13     private static void PermutationHelper(char[] cs, int i, ArrayList<String> list) {
14         if(i == cs.length-1){
15             //解空间的一个叶子结点
16             String val = String.valueOf(cs);
17             if (!list.contains(val))
18                 list.add(val);
19         }else{
20             for(int j = i; j < cs.length; ++j){
21                 swap(cs,i,j);
22                 PermutationHelper(cs, i+1, list);
23                 swap(cs,i,j);
24             }
25         }
26     }
27      public static void swap(char[] cs, int i, int j) {
28          char temp = cs[i];
29          cs[i] = cs[j];
30          cs[j] = temp;
31      }
32 }
原文地址:https://www.cnblogs.com/fankongkong/p/7453102.html