backTrack

3429 ワード

leetcodeでよく見られるbackTrack類タイトル:combination、subsets、permutation、Palindrome Partitioning.
1、combination
<1>leetcode39. Combination Sum
タイトルの説明:
Given a collection of candidate numbers ( candidates ) and a target number ( target ), find all unique combinations in candidates  where the candidate numbers sums to target .
Each number in candidates  may only be used once in the combination.
Note:
  • All numbers (including target ) will be positive integers.
  • The solution set must not contain duplicate combinations.
  • Input: candidates = [10,1,2,7,6,1,5], target = 8,
    A solution set is:
    [
      [1, 7],
      [1, 2, 5],
      [2, 6],
      [1, 1, 6]
    ]
    Input: candidates = [2,5,2,1,2], target = 5,
    A solution set is:
    [
      [1,2,2],
      [5]
    ]
    void backTrack(vector>& ans, vector& tmp, const vector& nums, int remain, int start){
        if(remain < 0) return;
        else if(remain == 0) ans.push_back(tmp);
        else{
            for(int i = start; i < nums.size(); i++){
                tmp.push_back(nums[i]);
                backTrack(ans, tmp, nums, remain - nums[i], i);
                tmp.pop_back();
            }
        }
    }
    
    vector> combinationSum(vector& nums, int target){
        vector> ans;
        vetcot temp;
        sort(nums.begin(), nums.end());
        backTrack(ans, temp, nums, target, 0);
        return ans;
    }

    <2>leetcode40. Combination Sum I
    Given a collection of candidate numbers ( candidates ) and a target number ( target ), find all unique combinations in candidates  where the candidate numbers sums to target .
    Each number in candidates  may only be used once in the combination.
    Note:
  • All numbers (including target ) will be positive integers.
  • The solution set must not contain duplicate combinations.
  • Input: candidates = [10,1,2,7,6,1,5], target = 8,
    A solution set is:
    [
      [1, 7],
      [1, 2, 5],
      [2, 6],
      [1, 1, 6]
    ]
    Input: candidates = [2,5,2,1,2], target = 5,
    A solution set is:
    [
      [1,2,2],
      [5]
    ]
    void backTrack(vector>& ans, vector& tmp, const vector& nums, int remain, int step){
            if(remain < 0) return;
            else if(remain == 0) ans.push_back(tmp);
            else{
                for(int i = step; i < nums.size(); i++){
                    if(i > step && nums[i - 1] == nums[i]) continue;
                    tmp.push_back(nums[i]);
                    backTrack(ans, tmp, nums, remain - nums[i], i + 1);
                    tmp.pop_back();
                }
            }
        }
        vector> combinationSum2(vector& candidates, int target) {
            vector> ans;
            vector tmp;
            sort(candidates.begin(), candidates.end());
            backTrack(ans, tmp, candidates, target, 0);
            return ans;
        }