Leetcode-**combination Sum using DFS algorithm

Source: Internet
Author: User

Given a set of candidate numbers (C) and a target number (T), find all unique combinations in C Where the candidate numbers sums to T.

The same repeated number is chosen from C unlimited number of times.

Note:

  • All numbers (including target) would be positive integers.
  • elements in a combination (a 1 ,  a 2 , ...,  a k ) must is in non-descending order. (Ie, a 1  ≤ a 2  ≤ ... ≤ a k ).
  • The solution set must not contain duplicate combinations.

For example, given candidate set2,3,6,7and Target7
A Solution set is:
[7] 

[2, 2, 3]

Class Solution {public:vector<vector<int> > Combinationsum (vector<int> &candidates, int target)        {vector<vector<int>> result;        Vector<int> path;        Result.clear ();        Path.clear ();        Sort (Candidates.begin (), Candidates.end ());        GetPath (Candidates,target,0,0,path,result);            return result; } void GetPath (vector<int> &candidates, int target,int depth,int sum,vector<int> &path,vector<v        Ector<int>> &result) {if (sum > Target) {return;            } if (sum = = target) {result.push_back (path);        Return        } int i;            for (i = depth; I < candidates.size (); i++) {path.push_back (candidates[i]);            GetPath (Candidates,target,i,sum+candidates[i],path,result);        Path.pop_back ();    } return; }};
The main is to find the array can add up equal to a specific number

Using the DFS algorithm, the sense that the DFS algorithm is still more characteristic, that is, in the process of searching, can only meet some of the data is satisfied, do not know the following situation

Through a depth of information, and a such as the sum value of the continuous downward search, if the search finally satisfied a certain condition, it means that the path is considered.

Leetcode-**combination Sum using DFS algorithm

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.