1. 程式人生 > >Backtracing: Subsets I+II, Permutations I+II

Backtracing: Subsets I+II, Permutations I+II

 Subsets

vector<vector<int>> res;
vector<vector<int>> subsets(vector<int>& nums) {
    vector<int> cur;
    backtrack(nums,cur,0);
    return res;
}
void backtrack(vector<int> &nums, vector<int> &cur, int start){
    res.push_back(cur);
    
for (int i=start;i<nums.size();++i){ cur.push_back(nums[i]); backtrack(nums,cur,i+1); cur.pop_back(); } }

 

Subsets II

有重複元素,先排序。同一層遞迴中相同元素跳過。

vector<vector<int>> res;
vector<vector<int>> subsetsWithDup(vector<int>& nums) {
    sort(nums.begin(),nums.end());
    vector
<int> cur; backtrack(nums,cur,0); return res; } void backtrack(vector<int> &nums, vector<int> &cur, int start){ res.push_back(cur); for (int i=start;i<nums.size();++i){ if (i>start && nums[i]==nums[i-1]) continue; cur.push_back(nums[i]); backtrack(nums,cur,i
+1); cur.pop_back(); } }

 

Subsets 時間複雜度

T(n) = T(n-1)+T(n-2)+...+T(1)+T(0) -> T(n) = O(2^n)

如果考慮 res.push_back(cur) 是時間 O(n),那麼總的時間複雜度為 O(n*2^n)

 

====================================================================

 Permutations

vector<vector<int>> res;
vector<vector<int>> permute(vector<int> &nums) {
    vector<int> cur;
    vector<bool> used(nums.size(),false);
    backtrack(nums,cur,used);
    return res;
}
void backtrack(vector<int> &nums, vector<int> &cur, vector<bool> &used){
    if (cur.size()==nums.size()){ res.push_back(cur); return; }
    for (int i=0;i<nums.size();++i){
        if (used[i]) continue;
        cur.push_back(nums[i]); used[i]=true;
        backtrack(nums,cur,used);
        cur.pop_back(); used[i]=false;
    }
}

也可以加個start用swap來做。