C + + template for all combination Problem set__c++

Source: Internet
Author: User

Firstly, the combination sum 1 & 4 are similar, and combination sum 2 & 3 are similar!!! Combination Sum 3 is the special case of combination sum 2, and the combination sum 4 return the count while combination S Um return all the combination!
K sum problem is a good extension for the combination sum problem, k-sum 1 are to return the count while K-sum 2 return all The possible results

Dp:when solve the problem return the count

Dfs:for return to all of the possible result

UPDATE@08/05/2016:

There are 2 interesting problem, let us check it now!

K Sum 1 & 2

Return the Count Given n distinct positive integers, integer k (k <= N) and a number target. Find k numbers where the sum is target. Calculate How many solutions there are?
return alll
Solution to Ksum-1:

Class Solution {public:/** * @param a:an integer array. * @param k:a positive integer (k <= Length (a)) * @param target:a integer * @return an integer * *
        NT Ksum (vector<int> A, int k, int target) {//Wirte your code here const int n = a.size (); /** Dp[i][j][target]: # of ways to start in vector[0..i-1], choose J elements to sum to target **/vector<v

        Ector<vector<int>>> DP (n + 1, vector<vector<int>> (k + 1, vector<int> (target + 1, 0))); for (int i = 1; I <= n; i++) {if (A[i-1] <= target) {for (int j = i; J <= N; j
                + +) {Dp[j][1][a[i-1]] = 1; 
            }}/** for position I, we can choose it or don't **/for (int i = 1; I <= n; i++) {
                    for (int j = min (i, k); j > 1; j--) {for (int p = 1; p <= target; p++) { Dp[i][j][P] = dp[i-1][j][p];
                    if (P-a[i-1] >= 0) {dp[i][j][p] + = dp[i-1][j-1][p-a[i-1]];
    }}} return Dp[n][k][target]; }
};

Update @ 2016/09/07
There is a more easy to grasp solution:

Class Solution {public:/** * @param a:an integer array. * @param k:a positive integer (k <= Length (a)) * @param target:a integer * @return an integer */int k
        Sum (vector<int> A, int k, int target) {//Wirte your code here const int n = a.size (); /** Dp[i][j][target]: # of ways to start in vector[0..i-1], choose J elements to sum to target **/vector<ve

        Ctor<vector<int>>> DP (n + 1, vector<vector<int>> (k + 1, vector<int> (target + 1, 0)));
        for (int i = 0; i < a.size (); i++) {dp[i][0][0] = 1; /** for position I, we can choose it or don't **/for (int i = 1; I <= n; i++) {for (int j = 1; J <= K; 
                    J + +) {for (int p = 1; p <= target; p++) {if (J > i) dp[i][j][p] = 0;
                    else dp[i][j][p] = dp[i-1][j][p];
           if (P-a[i-1] >= 0) {             DP[I][J][P] + = dp[i-1][j-1][p-a[i-1]];
    }}} return Dp[n][k][target]; }
};

Solution to Ksum-2:

class Solution {public:/** * @param a:an integer array. * @param k:a positive integer (k <= Length (a)) * @param target:a integer * @return A list of lists of Integ ER */vector<vector<int>> ksumii (vector<int> A, int k, int target) {VECTOR<VECTOR&L
        T;int>> ans;
        Vector<int> Curr;
        Helper (A, K, 0, Target, curr, ans);
    return ans; } void Helper (vector<int> A, int k, int start, int target, vector<int>& Curr, Vector<vector<int
        >> & ans) {if (k < 0 | | | Target < 0) {return;
            } if (k = = 0 && target = 0) {ans.emplace_back (Curr);
        Return
            for (int i = start; I <= a.size ()-K; i++) {curr.emplace_back (a[i));
            Helper (A, k-1, i + 1, target-a[i], curr, ans);
        Curr.pop_back (); }
    }
};

Problem Given A set of candidate numbers (C) and a target number (T), find all unique combinations in C where the CA Ndidate numbers sums to T. The same repeated number May is chosen from C unlimited number.

class Solution {public:vector<vector<int>> combinationsum (vector<int>& Amp
        candidates, int target) {sort (Candidates.begin (), Candidates.end ());
        vector<vector<int>> result;
        Vector<int> combination;
        DFS (candidates, target, result, combination, 0);
    return result; } void Dfs (vector<int>& nums, int target, vector<vector<int>>& result, vector<int>&am P
            combination, int begin) {if (!target) {result.push_back (combination);
        Return for (int i = begin; I < nums.size () && target >= nums[i]; i++) {Combination.push_back
            (Nums[i]);
            DFS (Nums, target-nums[i], result, combination, i);
        Combination.pop_back (); }
    }
};

Problem Given A collection of candidate numbers (C) and a target number (T), find all unique combinations in C where The candidate numbers sums to T. Each number in C is used once in the combination.

Class Solution {public:vector<vector<int>> combinationSum2 (vector<int>& candidates, int target
        ) {sort (Candidates.begin (), Candidates.end ());
        vector<vector<int>> result;
        Vector<int> combination;
        DFS (candidates, target, result, combination, 0);
    return result; } void Dfs (vector<int>& nums, int target, vector<vector<int>>& result, vector<int>&am P
            combination, int begin) {if (!target) {result.push_back (combination);
        Return for (int i = begin; I < nums.size () && target >= nums[i]; i++) {Combination.push_back
            (Nums[i]);
            Combinationsum1:dfs (Nums, target-nums[i], result, combination, i);
            DFS (Nums, target-nums[i], result, combination, i + 1);
            Combination.pop_back (); 
       Combinationsum1:no this line to filter the duplicate cases     while (I < nums.size () && nums[i] = = nums[i+1]) i++; }
    }
};

Problem 216 Find all possible combinations of K numbers ' add up to a number n, given ' only numbers from 1 to 9 can be used and each combination should is a unique set of numbers.

This problem are different from the 1 & 2, we choice is constrained to being [1,9], and our target are valid, then our EST number is just sum from 1 to 9, and we are the number 1 to 9 can only being choosed for one time. All in all, this problem was a special case of the combination problem 2

Class Solution {public
:
    vector<vector<int>> combinationSum3 (int k, int n) {
        vector<vector <int>> result;
        vector<int> path;
        DFS (1, path, result, K, n);
        return result;
    }

    void Dfs (int pos, vector<int>& path, vector<vector<int>>& result, int k, int n) {
        //cut edge
        if (n < 0) return;
        Valid cases
        if (n = = 0 && k = = Path.size ()) result.push_back (path);
        for (int i = pos; I <= 9; i++) {
            path.push_back (i);
            DFS (i + 1, path, result, K, n-i);
            Path.pop_back ();}}
;

Problem 377 Given An integer array with all positive numbers and no duplicates, find the number of possible combinations T Hat add up to a positive integer target.

This problem was just similar to the combination problem 1, we only need to return the count but not all possible resu Lt.

Dp[i]: Record the possible combination count to sum to target value of I

Class Solution {public
:
    int combinationSum4 (vector<int>& nums, int target) {
        vector<int> DP (target + 1);
        Dp[0] = 1;
        Sort (Nums.begin (), Nums.end ());
        for (int i = 1; I <= target; i++) {for
            (auto num:nums) {
                if (i < num) break;
                Dp[i] + = Dp[i-num]
            ;
        }
        return Dp.back ();
    }
;

Problem Given two integers n and K, return all possible combinations of k numbers out of 1 ... n.

This problem is the almost same as the problem combination sum 2, only with different ending conditions!

Class Solution {public
:
    vector<vector<int> > Combine (int n, int k) {
        vector<vector<int > > Res;
        vector<int> path;
        DFS (1, path, res, n, k);
        return res;
    }
    void Dfs (int pos, vector<int> &path, vector<vector<int> > &res, int n, int k) {
        if (path.siz E () = = k) res.push_back (path);
        else {for
            (int i = pos; I <= n; ++i) {
                path.push_back (i);
                DFS (i + 1, path, res, n, k);
                Path.pop_back (),}}}
;

Problem Letter combination Given A digit string, return all possible letter combinations this number could represen T. A mapping of Digit to letters (just as the telephone buttons) is given below.

class Solution {public:vector<string> lettercombinations (string digits) {VEC
        tor<string> Res;
        if (Digits.empty ()) return res;
        Vector<string> dict{"," "," abc "," Def "," Ghi "," JKL "," MnO "," PQRS "," TUV "," WXYZ "};
        DFS (digits, dict, 0, "", res);
    return res;
        } void Dfs (string digits, vector<string>& dict, int pos, string path, vector<string> &res) {
        if (pos = = Digits.size ()) res.push_back (path);
            else {string str = dict[digits[pos]-' 0 '];
                for (int i = 0; i < str.size (); ++i) {path.push_back (str[i));
                DFS (digits, dict, pos + 1, path, res);
            Path.pop_back (); }
        }
    }
};

Problem 254 Write A function that takes the integer n and return all possible combinations to its factors. Note:each combination ' s factors must to sorted ascending, for example:the factors of 2 and 6 are [2, 6], not [6, 2]. You may assume this n is always positive.

class Solution {public:vector<vector<int>> getfactors (int n) {VECTOR&L
        t;vector<int>> result;
        Vector<int> path;
        Helper (n, 2, path, result);
    return result;  } void helper (int remain, int start, vector<int> path, vector<vector<int>> &result) {if (remain = 1)
        {if (path.size () > 1) result.push_back (path);
                    else {for (int i = start; I <= remain; ++i) {if (remain% i = 0) {
                    Path.push_back (i);
                    Helper (remain/i, I, path, result);
                Path.pop_back (); }
            }
        }
    }
};
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.