comments | difficulty | edit_url |
---|---|---|
true |
中等 |
无重复字符串的排列组合。编写一种方法,计算某字符串的所有排列组合,字符串每个字符均不相同。
示例1:
输入:S = "qwe" 输出:["qwe", "qew", "wqe", "weq", "ewq", "eqw"]
示例2:
输入:S = "ab" 输出:["ab", "ba"]
提示:
- 字符都是英文字母。
- 字符串长度在[1, 9]之间。
我们设计一个函数
时间复杂度
class Solution:
def permutation(self, S: str) -> List[str]:
def dfs(i: int):
if i >= n:
ans.append("".join(t))
return
for j, c in enumerate(S):
if not vis[j]:
vis[j] = True
t[i] = c
dfs(i + 1)
vis[j] = False
ans = []
n = len(S)
vis = [False] * n
t = list(S)
dfs(0)
return ans
class Solution {
private char[] s;
private char[] t;
private boolean[] vis;
private List<String> ans = new ArrayList<>();
public String[] permutation(String S) {
s = S.toCharArray();
int n = s.length;
vis = new boolean[n];
t = new char[n];
dfs(0);
return ans.toArray(new String[0]);
}
private void dfs(int i) {
if (i >= s.length) {
ans.add(new String(t));
return;
}
for (int j = 0; j < s.length; ++j) {
if (!vis[j]) {
vis[j] = true;
t[i] = s[j];
dfs(i + 1);
vis[j] = false;
}
}
}
}
class Solution {
public:
vector<string> permutation(string S) {
int n = S.size();
vector<bool> vis(n);
string t = S;
vector<string> ans;
auto dfs = [&](this auto&& dfs, int i) {
if (i >= n) {
ans.emplace_back(t);
return;
}
for (int j = 0; j < n; ++j) {
if (!vis[j]) {
vis[j] = true;
t[i] = S[j];
dfs(i + 1);
vis[j] = false;
}
}
};
dfs(0);
return ans;
}
};
func permutation(S string) (ans []string) {
t := []byte(S)
n := len(t)
vis := make([]bool, n)
var dfs func(int)
dfs = func(i int) {
if i >= n {
ans = append(ans, string(t))
return
}
for j := range S {
if !vis[j] {
vis[j] = true
t[i] = S[j]
dfs(i + 1)
vis[j] = false
}
}
}
dfs(0)
return
}
function permutation(S: string): string[] {
const n = S.length;
const vis: boolean[] = Array(n).fill(false);
const ans: string[] = [];
const t: string[] = Array(n).fill('');
const dfs = (i: number) => {
if (i >= n) {
ans.push(t.join(''));
return;
}
for (let j = 0; j < n; ++j) {
if (vis[j]) {
continue;
}
vis[j] = true;
t[i] = S[j];
dfs(i + 1);
vis[j] = false;
}
};
dfs(0);
return ans;
}
/**
* @param {string} S
* @return {string[]}
*/
var permutation = function (S) {
const n = S.length;
const vis = Array(n).fill(false);
const ans = [];
const t = Array(n).fill('');
const dfs = i => {
if (i >= n) {
ans.push(t.join(''));
return;
}
for (let j = 0; j < n; ++j) {
if (vis[j]) {
continue;
}
vis[j] = true;
t[i] = S[j];
dfs(i + 1);
vis[j] = false;
}
};
dfs(0);
return ans;
};
class Solution {
func permutation(_ S: String) -> [String] {
var ans: [String] = []
let s = Array(S)
var t = s
var vis = Array(repeating: false, count: s.count)
let n = s.count
func dfs(_ i: Int) {
if i >= n {
ans.append(String(t))
return
}
for j in 0..<n {
if !vis[j] {
vis[j] = true
t[i] = s[j]
dfs(i + 1)
vis[j] = false
}
}
}
dfs(0)
return ans
}
}