[LeetCode] Backtracking

作者: SilentSummer | 来源:发表于2018-04-13 14:16 被阅读22次

    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

      1. Combination Sum I
      1. Combination Sum II
      1. Combination Sum III
      1. Combination Sum IV

    Permutations

    -31. Next Permutation

      1. Permutations
      1. Permutations II
      1. Permutation Sequence
      1. Palindrome Permutation
      1. Palindrome Permutation II
      1. Letter Case Permutation

    Subsets

    -78. Subsets

    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  []
    

    相关文章

      网友评论

        本文标题:[LeetCode] Backtracking

        本文链接:https://www.haomeiwen.com/subject/wrmckftx.html