Leetcode 46 Permutation Leetcode 78 Subsets
Permutation
题意
https://leetcode.com/problems/permutations/description/
返回[1,2,3]的全排列
首先既然是全排列对吧,我需要统计这个tmp数组里的元素个数是不是究竟等于3,然后iterate所有的数字对吧
class Solution {
public:
vector<vector<int>> arr;
vector<vector<int>> permute(vector<int>& nums) {
vector<int> tmp;
vector<bool> vis(nums.size(), false);
dfs(nums, tmp, vis);
return arr;
}
void dfs(vector<int>& nums, vector<int>& tmp, vector<bool>& vis){
if (tmp.size() == nums.size()) {
arr.push_back(tmp);
}
for(int i = 0; i < nums.size(); i++) {
if (!vis[i]) {
tmp.push_back(nums[i]);
vis[i] = true;
dfs(nums,tmp, vis);
tmp.pop_back();
vis[i] = false;
}
}
}
};
Subsets
题意,返回[1,2,3]所有的组合
我在dfs中每次某个位置的元素进行选或者不选的操作
class Solution {
public:
vector<vector<int>> arr;
vector<vector<int>> subsets(vector<int>& nums) {
vector<int> tmp;
dfs(0, nums, tmp);
return arr;
}
void dfs(int start, vector<int>& nums, vector<int>& tmp) {
arr.push_back(tmp);
for(int i = start; i < nums.size(); i++) {
tmp.push_back(nums[i]);
dfs(i+1, nums, tmp);
tmp.pop_back();
}
}
};