剑指 Offer 38:字符串的排列

This commit is contained in:
huangge1199 2021-06-22 12:55:15 +08:00
parent e46c5c83bf
commit 24ed143e35
2 changed files with 93 additions and 0 deletions

View File

@ -0,0 +1,73 @@
//输入一个字符串打印出该字符串中字符的所有排列
//
//
//
// 你可以以任意顺序返回这个字符串数组但里面不能有重复元素
//
//
//
// 示例:
//
// 输入s = "abc"
//输出["abc","acb","bac","bca","cab","cba"]
//
//
//
//
// 限制
//
// 1 <= s 的长度 <= 8
// Related Topics 回溯算法
// 👍 327 👎 0
package leetcode.editor.cn;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
//剑指 Offer 38:字符串的排列
public class ZiFuChuanDePaiLieLcof {
public static void main(String[] args) {
//测试代码
Solution solution = new ZiFuChuanDePaiLieLcof().new Solution();
}
//力扣代码
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
List<String> res = new LinkedList<>();
char[] c;
public String[] permutation(String s) {
c = s.toCharArray();
dfs(0);
return res.toArray(new String[res.size()]);
}
void dfs(int x) {
if (x == c.length - 1) {
res.add(String.valueOf(c)); // 添加排列方案
return;
}
HashSet<Character> set = new HashSet<>();
for (int i = x; i < c.length; i++) {
if (set.contains(c[i])) {
continue; // 重复因此剪枝
}
set.add(c[i]);
swap(i, x); // 交换 c[i] 固定在第 x
dfs(x + 1); // 开启固定第 x + 1 位字符
swap(i, x); // 恢复交换
}
}
void swap(int a, int b) {
char tmp = c[a];
c[a] = c[b];
c[b] = tmp;
}
}
//leetcode submit region end(Prohibit modification and deletion)
}

View File

@ -0,0 +1,20 @@
<p>输入一个字符串,打印出该字符串中字符的所有排列。</p>
<p>&nbsp;</p>
<p>你可以以任意顺序返回这个字符串数组,但里面不能有重复元素。</p>
<p>&nbsp;</p>
<p><strong>示例:</strong></p>
<pre><strong>输入:</strong>s = &quot;abc&quot;
<strong>输出:[</strong>&quot;abc&quot;,&quot;acb&quot;,&quot;bac&quot;,&quot;bca&quot;,&quot;cab&quot;,&quot;cba&quot;<strong>]</strong>
</pre>
<p>&nbsp;</p>
<p><strong>限制:</strong></p>
<p><code>1 &lt;= s 的长度 &lt;= 8</code></p>
<div><div>Related Topics</div><div><li>回溯算法</li></div></div>\n<div><li>👍 327</li><li>👎 0</li></div>