当前位置:网站首页>面试题 08.07. 无重复字符串的排列组合 ●●
面试题 08.07. 无重复字符串的排列组合 ●●
2022-08-02 23:50:00 【keep_fan】
面试题 08.07. 无重复字符串的排列组合 ●●
描述
无重复字符串的排列组合。编写一种方法,计算某字符串的所有排列组合,字符串每个字符均不相同。
示例
输入:S = “qwe”
输出:[“qwe”, “qew”, “wqe”, “weq”, “ewq”, “eqw”]
题解
1. used 标记 + 回溯
class Solution {
public:
vector<string> ans;
string path;
int cnt = 1;
void backtrack(string& s, vector<bool>& used, int n){
if(ans.size() == cnt) return; // 全排列数 = n!
if(path.length() == n){
// 一个字符串排列完成
ans.emplace_back(path);
return;
}
for(int i = 0; i < n; ++i){
if(used[i] == false){
path.push_back(s[i]); // 排列
used[i] = true;
backtrack(s, used, n);
used[i] = false; // 回溯
path.pop_back();
}
}
}
vector<string> permutation(string S) {
int n = S.length();
vector<bool> used(n, false);
for(int i = n; i >= 1; --i){
// 计算全排列数
cnt *= i;
}
backtrack(S, used, n);
return ans;
}
};
2. 交换法 + 回溯
若字符串长度为 n,将第一个字母分别与后面每一个字母进行交换,生成 n 种不同的全排列;
再用第二个元素与后面每一个元素进行交换,生成 n - 1 种不同的全排列……
…
注意:
递归的停止条件为 idx == s.length()
递归的第一个参数为 idx+1
class Solution {
public:
vector<string> ans;
void backtrack(int idx, string& s){
if(idx == s.length()){
// 一个字符串交换排列完成
ans.emplace_back(s);
return;
}
for(int i = idx; i < s.length(); ++i){
// 从idx开始,分别与idx进行交换
swap(s[i], s[idx]);
backtrack(idx+1, s); // 交换下一个字符
swap(s[i], s[idx]); // 回溯
}
}
vector<string> permutation(string S) {
backtrack(0, S);
return ans;
}
};
边栏推荐
- 【Autosar RTM】
- CIO修炼手册:成功晋升CIO的七个秘诀
- 合并两个excel表格工具
- js基础知识整理之 —— 闭包
- Canonical correlation analysis of CCA calculation process
- 十三、数据回显
- 基于rt-thread studio的STM32裸机开发——LED
- 浅谈I2C知识
- 2022 Shandong International Youth Eye Health Industry Exhibition, Vision Health Exhibition, Optometry Exhibition
- 可编程逻辑控制器(PLC) : 基础、类型和应用
猜你喜欢
随机推荐
微信小程序实现lot开发09 接入微信登录
TensorFlow学习记录(一):基本介绍
VMware workstation program starts slowly
@GetMapping、@PostMapping、@PutMapping、@DeleteMapping的区别
d合并json
Nuxt 所有页面都设置上SEO相关标签
我们来浅谈代码语言的魅力
js基础知识整理之 —— 变量和数据类型
What is the matter that programmers often say "the left hand is knuckled and the right hand is hot"?
厌倦了安装数据库?改用 Docker
【软考 系统架构设计师】软件架构设计① 软件架构的概念
电压传感器: 工作原理、类型及电路图
2022中国眼博会,山东眼健康展,视力矫正仪器展,护眼产品展
matplotlib中的3D绘图警告解决:MatplotlibDeprecationWarning: Axes3D(fig) adding itself to the figure
【系统架构设计师】第三章 数据库系统
十二、form表单的提交
剑指 Offer 21. 调整数组顺序使奇数位于偶数前面
Heartwarming AI Review (1)
js显示隐藏手机号
用了这么多年的LinkedList,作者说自己从来不用它?为什么?









