Article Directory
Method 1: dfs + pruning: time O( n! N!n ! ), space O(n)
Problem-solving ideas:
- Full arrangement of strings, insert the structure of each different arrangement into the array
- Loop through the array through dfs + and swap element positions to achieve full arrangement
- During the full arrangement process, multiple elements in the array may occupy the same position repeatedly, resulting in duplicate results
- Therefore, a fixed-size array is used, and the position of each row corresponds to the subscript ++
class Solution {
public:
vector<string> ans;
vector<string> permutation(string s)
{
dfs(s, 0);
return ans;
}
void dfs(string& s, int pos)
{
// 直接对 s 进行全排列
if (pos == s.size() - 1)
{
ans.push_back(s);
return;
}
int board[1024] = {
0 };
for (int i = pos; i < s.size(); ++i)
{
if (board[s[i]] != 0)
continue;
board[s[i]]++;
swap(s[i], s[pos]);
dfs(s, pos + 1);
swap(s[i], s[pos]);
}
}
};