Leetcode - Permutations I,II
全排列问题是回溯的典型例题:
1.可行解的组成形式是给定数组中的所有数的组合,故而大小上可以作为可行解判定条件
2.每次需要在剩下可被选中的集合中选择一个,创建mask数组
class Solution { public: void dfs(vector<vector<int>> &vct, vector<int> &cur, vector<int>& nums,vector<int> & used) { if (cur.size() == nums.size()) { vct.push_back(cur); return; } for (int i = 0; i < nums.size(); ++i) { if (used[i] == 0) { cur.push_back(nums[i]); used[i] = 1; dfs(vct, cur, nums, used); used[i] = 0; cur.pop_back(); } } } vector<vector<int>> permute(vector<int>& nums) { vector<vector<int>> vct; int n = nums.size(); if (n <= 0) return vct; vector<int> cur; vector<int> used(n, 0); dfs(vct, cur, nums, used); return vct; } };
Leetcode - 047. Permutations II
diff : 需要考虑val1 = val2 的情况,需要sort将相同元素聚类,然后可以参考前文 Leetcode - 040. Combination Sum II 去重的方法
class Solution { public: void dfs(vector<vector<int>> &vct, vector<int> &cur, vector<int>& nums, vector<int> & used) { if (cur.size() == nums.size()) { vct.push_back(cur); return; } for (int i = 0; i < nums.size(); ++i) { if (used[i] == 0) { int pre_index = i - 1; bool repeated = false; while (pre_index >= 0 && nums[pre_index] == nums[i]) { if (used[pre_index] == 0) { repeated = true; break; } --pre_index; } if (repeated) continue; cur.push_back(nums[i]); used[i] = 1; dfs(vct, cur, nums, used); used[i] = 0; cur.pop_back(); } } } vector<vector<int>> permuteUnique(vector<int>& nums) { vector<vector<int>> vct; vector<int> cur; int n = nums.size(); if (n <= 0) return vct; vector<int> used(n, 0); dfs(vct, cur, nums, used); return vct; } };
相关推荐
aanndd 2020-08-12
aanndd 2020-07-26
aanndd 2020-07-08
zangdaiyang 2020-07-04
yaohustiAC 2020-06-28
us0 2020-06-28
yaohustiAC 2020-06-28
zangdaiyang 2020-06-28
Clairezz 2020-06-28
嗡汤圆 2020-06-26
嗡汤圆 2020-06-21
aanndd 2020-06-16
aanndd 2020-06-16
码墨 2020-06-16
yaohustiAC 2020-06-11
zangdaiyang 2020-06-10
jiayuqicz 2020-06-09
yaohustiAC 2020-06-06
heray0 2020-06-04