无重复字符串的排列组合。编写一种方法,计算某字符串的所有排列组合,字符串每个字符均不相同。
示例1:
输入:S = "qwe"
输出:["qwe", "qew", "wqe", "weq", "ewq", "eqw"]
示例2:
输入:S = "ab"
输出:["ab", "ba"]
提示:
- 字符都是英文字母。
- 字符串长度在[1, 9]之间。
1.回溯
python:
class Solution:
def permutation(self, S: str) -> List[str]:
res = []
A = list(S)
flag = [0 for i in range(len(A))]
def backtrace(A, arr):
if len(arr) == len(A):
res.append(''.join(arr))
for i in range(len(A)):
if not flag[i]:
arr.append(A[i])
flag[i] = 1
backtrace(A, arr)
arr.pop()
flag[i] = 0
backtrace(A, [])
return res
Java:
class Solution {
public String[] permutation(String S) {
List<String> result = new ArrayList<String>();
boolean[] flag = new boolean[S.length()];
backtrack(result, flag, S, "");
return result.toArray(new String[result.size()]);
}
public void backtrack(List<String> a, boolean[] flag, String s, String t)
{
if(s.length() == t.length())
{
a.add(t);
}
for(int i = 0; i < s.length(); i++)
{
if(!flag[i])
{
flag[i] = true;
backtrack(a, flag, s, t+s.charAt(i));
flag[i] = false;
}
}
}
}
2.交换法
Python:
class Solution:
def permutation(self, S: str) -> List[str]:
res = []
a = list(S)
def swap(arr, j):
if j == len(arr):
res.append(''.join(arr))
return
else:
for i in range(j, len(arr)):
arr[i], arr[j] = arr[j], arr[i]
swap(arr, j+1)
arr[i], arr[j] = arr[j], arr[i]
swap(a, 0)
return res
Java:
class Solution {
public String[] permutation(String S) {
List<String> result = new ArrayList<String>();
char[] ch = new char[S.length()];
for(int i = 0; i < S.length(); i++)
{
ch[i] = S.charAt(i);
}
boolean[] flag = new boolean[S.length()];
backtrack(result, ch, 0);
return result.toArray(new String[result.size()]);
}
public void backtrack(List<String> a, char[] ch, int p)
{
if(p == ch.length)
{
a.add(String.valueOf(ch));
}
for(int i = p; i < ch.length; i++)
{
swap(ch, i, p);
backtrack(a, ch, p+1);
swap(ch, i, p);
}
}
public void swap(char[] ch, int i, int j)
{
char t = ch[i];
ch[i] = ch[j];
ch[j] = t;
}
}
留言