1 46. 全排列
AC代码:
class Solution {
public:
bool vis[22];
vector<vector<int>> permute(vector<int>& nums) {
vector<vector<int>> ans;
vector<int> now;
dfs(0,nums,now,ans);
return ans;
}
void dfs(int u,vector<int>& nums,vector<int>& now,vector<vector<int>>& ans)
{
if(u == nums.size())
{
for(int i = 0;i < now.size();i++)
cout << i << ' ';
cout << endl;
ans.push_back(now);
}
for(int i = 0; i < nums.size();i++)
{
if(!vis[nums[i]+10])
{
now.push_back(nums[i]);
vis[nums[i]+10] = 1;
dfs(u+1,nums,now,ans);
now.pop_back();
vis[nums[i]+10] = 0;
}
}
}
};
2 78. 子集
我的思路:从n个数中去k个数的组合问题,其中需要遍历k,AC代码:
class Solution {
public:
vector<vector<int> > ans;
vector<int> path;
bool vis[20];
void dfs(int u,int k,int startidx,vector<int>& nums)
{
if(u == k + 1)
{
ans.push_back(path);
return;
}
for(int i = startidx; i < nums.size();i++)
{
if(!vis[i])
{
path.push_back(nums[i]);
vis[i] = 1;
dfs(u+1,k,i+1,nums);
vis[i] = 0;
path.pop_back();
}
}
}
vector<vector<int>> subsets(vector<int>& nums) {
int max_num = nums.size();
for(int k = 0; k <= max_num; k++)
dfs(0,k,0,nums);
vector<int> tmp;
ans.push_back(tmp);
return ans;
}
};
3 17. 电话号码的字母组合
一开始我的dfs里面有vis[],即每一个字母只可以访问一次,但是过不了比如 "222" 这样测试样例,后来删掉就过了,AC代码:
class Solution {
public:
vector<string> ans;
string path;
string a[10] = {"abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};
void dfs(int u,string digits)
{
if(u == digits.size())
{
ans.push_back(path);
return;
}
for(int i = 0; i < a[digits[u]-'0'-2].size();i++)
{
char now_char = a[digits[u]-'0'-2][i];
int now_char_idx = now_char - 'a';
path.push_back(now_char);
dfs(u+1,digits);
path.pop_back();
}
}
vector<string> letterCombinations(string digits) {
if(digits == "")return ans;
dfs(0,digits);
return ans;
}
};