题目描述
输入一个字符串,打印出该字符串中字符的所有排列。
你可以以任意顺序返回这个字符串数组,但里面不能有重复元素。
示例:
输入:s = "abc"
输出:["abc","acb","bac","bca","cab","cba"]
限制:
1 <= s 的长度 <= 8
Java代码
class Solution { private List<String> res = new ArrayList<>(); public String[] permutation(String s) { char[] c = s.toCharArray(); A(c, 0, c.length - 1); return res.toArray(new String[0]); } public void A(char[] c, int start, int end) { if (start >= end) { res.add(new String(c)); return; } // 固定start,即start~end依次枚举,每次从后面拿一个跟start进行交换,然后让交换后的start + 1~end这些字符进行全排列 for (int i = start; i <= end; i++) { if (canSwap(c, start, i)) { swap(c, start, i); A(c, start + 1, end); swap(c, i, start); } } } public void swap(char[] c, int i, int j) { char tmp = c[i]; c[i] = c[j]; c[j] = tmp; } public boolean canSwap(char[] c, int i, int j) { char target = c[j]; // 能交换的前提是:前面不能够出现跟当前数相同的数 for (int k = i; k < j; k++) { if (c[k] == target) { return false; } } return true; } }
评测结果
力扣链接:https://leetcode.cn/problems/zi-fu-chuan-de-pai-lie-lcof/
标签:排列,end,String,int,力扣,start,38,字符串 From: https://www.cnblogs.com/pengsay/p/16609908.html