[LeetCode] Backtracking

Usually, the main idea of the so-called backtraking is to generate parallel routes to output each element of the num vector, and finish task of each routine separately.

Backtracking

Combinations

-77. Combinations
- 39. Combination Sum I
- 40. Combination Sum II
- 216. Combination Sum III
- 377. Combination Sum IV

Permutations

-31. Next Permutation
- 46. Permutations
- 47. Permutations II
- 60. Permutation Sequence
- 266. Palindrome Permutation
- 267. Palindrome Permutation II
- 784. Letter Case Permutation

Subsets

-78. Subsets
- 90. Subsets II

Permutations

template 1 - for non-duplicate cases

For the first template, we should build a helper function with 5 elements, including:
- input number vector,
- backtracking level,
- a vector to record each element being visited or not,
- a updated output vector,
- the final result.

In the helper function, if the current level equals the input vector’s size, then add the current output vector to the final result vector. Otherwise, find a non-visited element and generate a new route by call the helper function agagin, then backtrack to the state before generating this new route. This is very important and why the method is called as “backtracking”!

    vector<vector<int>> permute(vector<int>& nums) {
        vector<vector<int>> res;
        vector<int> output;
        vector<bool> visited (nums.size(), false);
        permuteDFS(nums, 0, visited, output, res);
        return res;
    }
    void permuteDFS(vector<int>& nums, int level, vector<bool>&  visited, vector<int>& output, vector<vector<int>>& res) {
        // if (output.size() == nums.size() )
        if (level == nums.size() )
            res.push_back(output);
        else {
            for (int i = 0; i < nums.size(); i++) {
                if (!visited[i]) {
                    visited[i] = true;
                    output.push_back(nums[i]);
                    permuteDFS(nums, level+1, visited, output, res);
                    output.pop_back();
                    visited[i] = false;
                }
            }
        }
    }

template 2 - to avoid duplicates

1st idea to use set to store the output vector and transfer to vector. 3 lines are key changes to the template 1.

set<vector<int>> res;

return vector<vector<int>> (res.begin(), res.end());

res.insert(output);
    vector<vector<int>> permuteUnique(vector<int>& nums) {
        set<vector<int>> res;
        vector<bool> visited(nums.size(), false);
        vector<int> output;
        permuteDFS(nums, 0, visited, output, res);
        return vector<vector<int>> (res.begin(), res.end());
    }
    void permuteDFS(vector<int>& nums, int level, vector<bool>& visited, vector<int>& output, set<vector<int>>& res) {
        if (level == nums.size()) 
            res.insert(output);
        else {
            for (int i = 0; i < nums.size(); i++) {
                if (!visited[i]) {
                    visited[i] = true;
                    output.push_back(nums[i]);
                    permuteDFS(nums, level+1, visited, output, res);
                    output.pop_back();
                    visited[i] = false;
                }
            }
        }
    }

Subsets

The following is solution with recursion. There are non-recursive solutions for subsets.

template 1 - for non-duplicate cases

    vector<vector<int>> subsets(vector<int>& nums) {
        vector<vector<int>> res;
        vector<int> output;
        sort(nums.begin(), nums.end());
        permuteDFS(nums, 0, output, res);
        return res;
    }
    void permuteDFS(vector<int>& nums, int level, vector<int>& output, vector<vector<int>>& res) {
        // not add
        res.push_back(output);
        // add
            for (int i = level; i < nums.size(); i++) {   
                output.push_back(nums[i]);
                permuteDFS(nums, i+1, output, res);
                output.pop_back();
            }
    }
                        []        
                   /          \        
                  /            \     
                 /              \
              [1]                []
           /       \           /    \
          /         \         /      \        
       [1 2]       [1]       [2]     []
      /     \     /   \     /   \    / \
  [1 2 3] [1 2] [1 3] [1] [2 3] [2] [3] []

template 2 - for duplicate cases

    vector<vector<int>> subsets(vector<int>& nums) {
        vector<vector<int>> res;
        vector<int> output;
        sort(nums.begin(), nums.end());
        permuteDFS(nums, 0, output, res);
        return res;
    }
    void permuteDFS(vector<int>& nums, int level, vector<int>& output, vector<vector<int>>& res) {
        // not add
        res.push_back(output);
        // add
            for (int i = level; i < nums.size(); i++) {   
                output.push_back(nums[i]);
                permuteDFS(nums, i+1, output, res);
                output.pop_back();
                while (i + 1 < numsS.size() && nums[i] == nums[i + 1]) ++i;
            }
    }
                        []        
                   /          \        
                  /            \     
                 /              \
              [1]                []
           /       \           /    \
          /         \         /      \        
       [1 2]       [1]       [2]     []
      /     \     /   \     /   \    / \
  [1 2 2] [1 2]  X   [1]  [2 2] [2] X  []
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值