[Leetcode series] combination and enumeration problems

Source: Internet
Author: User

Given a number of columns (unordered) and a target value, we can find all possible combinations and combinations equal to or equal to the target value. The number in the array can be reused.

Algorithm concept: recursion.

  1. Sorts arrays from small to large;
  2. Make I = start subscript (initial 0), for each number,
    1. If the value is equal to the target value, add the value to the cache result and add the cached result to the output queue. Then, delete the value from the cache result;
    2. If it is smaller than the target value, add this number to the cache result and call this algorithm recursively. The target value is updated to the difference value and the start subscript is I;
    3. If it is greater than the target value, the algorithm returns.

Understanding of 2.2: If this number is smaller than the target value, because the algorithm is cyclic recursion, the initial subscript must not be smaller than I (otherwise, repetition occurs ).

Code:

 1 class Solution { 2 public: 3     vector<vector<int> > combinationSum(vector<int> &candidates, int target) { 4         vector<int> A(candidates); 5         vector<int> oneRes; 6         vector<vector<int> > result; 7         sort(A.begin(), A.end()); 8         helper(A, target, oneRes, result, 0); 9         return result;10     }11     12     void helper(vector<int> A, int target, vector<int> &oneRes, vector<vector<int> > &result, int start) {13         for (int i = start; i < A.size(); i++) {14             if (A[i] == target) {15                 oneRes.push_back(A[i]);16                 result.push_back(oneRes);17                 oneRes.pop_back();18             }19             else if (A[i] < target) {20                 oneRes.push_back(A[i]);21                 helper(A, target-A[i], oneRes, result, i);22                 oneRes.pop_back();23             }24             else return;25         }26     }27 };

 

[Leetcode series] combination and enumeration problems

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.