字符串的排列
题目描述
输入一个字符串,按字典序打印出该字符串中字符的所有排列。例如输入字符串abc,则打印出由字符a,b,c所能排列出来的所有字符串abc,acb,bac,bca,cab和cba。
值得注意的是字符串中无重复字符。相关问题LeetCode 47 Permutations II 带重复字符的排列问题
解法
求整个字符串的排列,可以分为两步。第一步求出所有可能出现在第一个位置的字符,即将第一个字符与后面的所有字符交换;第二步固定第一个字符,递归求解后续的所有字符排列。
LeetCode 46 解法笔记
LeetCode 47 解法笔记
import java.util.ArrayList;
import java.util.TreeSet;
public class Solution {
public ArrayList<String> Permutation(String str)
{
ArrayList<String> result = new ArrayList<>();
if(str.length() <= 0)return result;
char[] chars = str.toCharArray();
TreeSet<String> set = new TreeSet<>();
helper(chars, 0, set);
result.addAll(set);
return result;
}
private static void helper(char[] chars, int index, TreeSet<String> set)
{
if(chars == null || chars.length == 0 || index < 0 || index > chars.length - 1)
return;
if(index == chars.length - 1)
set.add(String.valueOf(chars));
else
{
for(int i = index; i <= chars.length - 1; ++i)
{
swap(chars, index, i);
helper(chars, index+1, set);
swap(chars, index, i);
}
}
}
private static void swap(char[] chars, int i, int j){
char tmp = chars[i];
chars[i] = chars[j];
chars[j] = tmp;
}
}
本题扩展
- 字符的组合问题
- 输入一个含有8个数字的数组,判断有没有可能把这8个数字分别放到正方体的8个定点,使得正方体上三组相对的面四个定点的和都相等。
~每天都要加油鸭

浙公网安备 33010602011771号