DFS-leetcode combination sum I/I

Source: Internet
Author: User

Deep Priority Search (DFS) is a search algorithm. The earliest contact with DFS should be in the traversal of a binary tree. The first, middle, and last traversal of a binary tree actually belongs to the depth-first traversal. The essence is the depth-first search, later, we saw a more pure depth-first search algorithm in the depth-first traversal of the image.

We usually look at tracing and DFS in the same way. We can use an equation to represent their relationship: backtracking = DFS + pruning. Therefore, the backtracking method is an extension of DFS. It aims to accelerate DFS by means of pruning so that if the tracing condition is met in the deep priority search process and the leaf node does not need to be found, this path is truncated. In fact, even if there is no pruning, DFS is also a backtracking process when it rolls back from the lower layer to the upper layer. Usually, some variables are in the state at this time. DFS is usually implemented in recursive form, which is intuitive or non-recursive. However, you usually need to store search paths by using a group of auxiliary data structures (such as stacks.

The following two topics on leetcode are used to demonstrate the application of DFS:

Question 1 combination sum I: There is a positive integer set C and a target number T (t is also a positive integer ). Select a number from C so that the sum is exactly the same as T (each number in C can be obtained several times) and calculate all different number fetch schemes.

Example: c = {2, 3, 6, 7} t = 7

Res = {[7],

[2, 2, 3]}

Class solution {public: vector <int> combinationsum (vector <int> & candidates, int target) {vector <int> TMP; sort (candidates. begin (), candidates. end (); // first sort the number of candidates in C in ascending order to prepare sou = candidates for subsequent pruning; DFS (TMP, target, 0); Return res;} PRIVATE: vector <vector <int> res; // Save the final result vector <int> sou; int sum (vector <int> TMP) {// calculates the sum and INT r = 0; for (INT I = 0; I! = TMP. size (); ++ I) R + = TMP [I]; return r;} void DFS (vector <int> & TMP, int tag, int L) {If (L = sou. size () // return; int tot = sum (TMP); If (TOT = tag) {res. push_back (TMP); return;} else if (TOT> tag) // pruning return; else {for (INT I = L; I! = Sou. size (); ++ I) {// Since each number in C can be selected multiple times, I starts from L instead of L + 1 TMP. push_back (SOU [I]); DFS (TMP, Tag, I); TMP. pop_back (); // trace back to the TMP status }}}};

Question 2 combination sum II: The difference from Question 1 is that each number in set C can only be obtained once at most, but there can be repeated numbers in C.

Example: c = {, 5} t = 8

Res = {[1, 7]
[1, 2, 5]
[2, 6]
[1, 1, 6]}

Question 2 can use a method similar to the question, but since each number in question 2 can only be obtained once, the for loop in the DFS function, I should start from L + 1 and represent taking the next number. But the problem is that there will be repeated number fetch solutions in the results. Take the above example for analysis: There are two ones in C that can be selected, the first 1 and 7 are an optional scheme (1 + 7 = 8), and the second 1 and 7 are also an optional scheme. According to the above algorithm, [] appears twice in the result. Of course, the final result can be de-duplicated (if C ++ is used, sort-> unique-> erase can be implemented ). Unfortunately, this solution times out. The solution for timeout is not to add repeated solutions to the result set, which avoids deduplication. The AC code is as follows:

Class solution {public: vector <int> combinationsum2 (vector <int> & candidates, int target) {vector <int> TMP; For (INT I = 0; I! = Candidates. size (); ++ I) {// mm is a map, and the key is the number of optional values in C, value is the number of mm [candidates [I] ++;} For (Map <int, int >:: iterator it = mm. begin (); it! = Mm. end (); ++ it) {for (INT I = 0; I <it-> second; ++ I) {TMP. push_back (IT-> first); DFS (TMP, target, it) ;}for (INT I = 0; I <it-> second; ++ I) {// trace back to TMP. pop_back () ;}}return res;} PRIVATE: vector <int> res; // Save the final result Map <int, int> mm; int sum (vector <int> TMP) {// calculates the sum and INT r = 0; For (INT I = 0; I! = TMP. size (); ++ I) R + = TMP [I]; return r;} void DFS (vector <int> & TMP, int tag, Map <int, int>:: iterator it) {If (IT = mm. end () // return; int tot = sum (TMP); If (TOT = tag) {res. push_back (TMP); return;} else if (TOT> tag) // pruning return; else {for (++ it; it! = Mm. end (); ++ it) {for (INT I = 0; I <it-> second; ++ I) {TMP. push_back (IT-> first); DFS (TMP, tag, it) ;}for (INT I = 0; I <it-> second; ++ I) {// trace back to TMP. pop_back ();}}}}};
Key code:

For (++ it; it! = Mm. end (); ++ it) {for (INT I = 0; I <it-> second; ++ I) {TMP. push_back (IT-> first); DFS (TMP, tag, it) ;}for (INT I = 0; I <it-> second; ++ I) {// trace back to TMP. pop_back ();}}
The outer loop indicates that a number is selected from C in sequence. The first loop in the inner layer indicates that the number in C can be retrieved several times. The second loop in the inner layer indicates that if the previous number is not selected, to restore the status, delete the number of saved items (delete the number of items added ).





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.