LeetCode DAY23(39. Combination Sum&40. Combination Sum II&131. Palindrome Partitioning)

Preface

This is a new day to continue my backtracking algorithm journey.
Learn something new and keep reviewing what I learnt before.

1. Combination Sum

LeetCode Link: 39. Combination Sum
Given an array of distinct integers candidates and a target integer target, return a list of all unique combinations of candidates where the chosen numbers sum to target. You may return the combinations in any order.

The same number may be chosen from candidates an unlimited number of times. Two combinations are unique if the
frequency
of at least one of the chosen numbers is different.

The test cases are generated such that the number of unique combinations that sum up to target is less than 150 combinations for the given input.

Analysis and Solution

Recursion

LeetCode C++ as followings Recursion

class Solution {
private:
    vector<vector<int>> result;//global variation; define a array to store results
    vector<int> path;//global variation; define a array to store single result
    void backtracking(vector<int>& candidates, int target, int sum, int startIndex) {//recursion function with candidates and target and sum(sum of value of path)and startIndex(the beginning of for loop) as parameters
        if (sum > target) {//remove case
            return;
        }
        if (sum == target) {//import the right result
            result.push_back(path);
            return;
        }

        for (int i = startIndex; i < candidates.size(); i++) {//for loop to traverse
            sum += candidates[i];//get the sum of process
            path.push_back(candidates[i]);//import to path
            backtracking(candidates, target, sum, i); // recursion function; "i" not "i+1" which indicates it can repeatly use current value.
            sum -= candidates[i];//backtrack
            path.pop_back();//backtrack
        }
    }
public:
    vector<vector<int>> combinationSum(vector<int>& candidates, int target) {//main function with two parameters
        result.clear();
        path.clear();
        backtracking(candidates, target, 0, 0);//import the parameters
        return result;
    }
};

2. Combination Sum II

LeetCode Link: 40. Combination Sum II
Given a collection of candidate numbers (candidates) and a target number (target), find all unique combinations in candidates where the candidate numbers sum to target.

Each number in candidates may only be used once in the combination.

Note: The solution set must not contain duplicate combinations.

Analysis and Solution

Recursion

LeetCode C++ as followings Recursion

class Solution {
private:
    vector<vector<int>> result;//store results
    vector<int> path;//store single result
    void backtracking(vector<int>& candidates, int target, int sum, int startIndex, vector<bool>& used) {//recursion; sum(sum of value of path) startIndex(beginning of for loop) used(remove duplicate)
        if (sum == target) {//terminate condition
            result.push_back(path);
            return;
        }
        for (int i = startIndex; i < candidates.size() && sum + candidates[i] <= target; i++) {
            // used[i - 1] == true,indicates candidates[i - 1] of same branch of tree was used
            // used[i - 1] == false,indicates candidates[i - 1] of same layer of tree was used
            // skip same layer of tree
            if (i > 0 && candidates[i] == candidates[i - 1] && used[i - 1] == false) {
                continue;
            }
            sum += candidates[i];
            path.push_back(candidates[i]);
            used[i] = true;//remove duplicate
            backtracking(candidates, target, sum, i + 1, used); // "i+1" element only was used once
            used[i] = false;
            sum -= candidates[i];
            path.pop_back();
        }
    }

public:
    vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
        vector<bool> used(candidates.size(), false);
        path.clear();
        result.clear();
        // sort elements of candidates let same elements next to each other
        sort(candidates.begin(), candidates.end());
        backtracking(candidates, target, 0, 0, used);//recursion and import parameters
        return result;
    }
};

3. Palindrome Partitioning

LeetCode Link: 131. Palindrome Partitioning
Given a string s, partition s such that every substring of the partition is a palindrome. Return all possible palindrome partitioning of s.

Analysis and Solution

Recursion

LeetCode C++ as followings Recursion

class Solution {
private:
    vector<vector<string>> result;//store results
    vector<string> path; // store single palindrome result
    void backtracking (const string& s, int startIndex) {
        // if beignning > s; which indicates that have found one plan
        if (startIndex >= s.size()) {
            result.push_back(path);
            return;
        }
        for (int i = startIndex; i < s.size(); i++) {//traverse
            if (isPalindrome(s, startIndex, i)) {   // judge if it is palindrome
                // get substring in [startIndex,i] from s 
                string str = s.substr(startIndex, i - startIndex + 1);
                path.push_back(str);
            } else {                                // not palindrome;skip
                continue;
            }
            backtracking(s, i + 1); // recursion at i+1
            path.pop_back(); // backtrack; pop substring
        }
    }
    bool isPalindrome(const string& s, int start, int end) {//judge if it is palindrome
        for (int i = start, j = end; i < j; i++, j--) {//double pointer to judge
            if (s[i] != s[j]) {
                return false;
            }
        }
        return true;
    }
public:
    vector<vector<string>> partition(string s) {//main function with parameter
        result.clear();
        path.clear();
        backtracking(s, 0);
        return result;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值