[C + +] leetcode:83 combinations (backtracking method)

Source: Internet
Author: User

Topic:

Given-integers n and K, return all possible combinations of K numbers out of 1 ... n.

For example,
If N = 4 and k = 2, a solution is:

[  [2,4],  [3,4], [  2,3],  [up],  [1,3],  [1,4],]

Thought: Backtracking method

Constructs an auxiliary function, Combine_helper.

(1) Recursion once, fill in a number

(2) Fill in the number, cannot be less than the current number of values, to prevent duplication

(3) Backtracking: Pop_back () The last number added, back to the previous level

(4) The end condition, when the number is filled with k number, the current completed, backtracking.

About the specific implementation of backtracking, this article has an animation, explained very vivid: backtracking


Attention:

1. Note that the number we fill in must be incremented, otherwise it will result in duplicate numbers.

2. Grasp the essence of retrospective thinking. Pop_back is critical. Go back to the previous level.

Complexity: non-deterministic polynomial time complexity class, NP problem

AC Code:

Class Solution {public:    vector<vector<int> > Combine (int n, int k) {        vector<vector<int> > ret;        if (n = = 0 | | k = = 0 | | n < k) return ret;        vector<int> tmp;        Combine_helper (0, 0, N, K, TMP, ret);        return ret;    } Private:    void Combine_helper (int start, int num, int n, int k, vector<int> tmp, vector<vector<int> > & ret)    {        if (num = = k)        {            ret.push_back (TMP);            return;        }                for (int i = start; i < n; i++)        {            tmp.push_back (i+1);            Combine_helper (i+1, Num+1, N, K, TMP, ret);            Tmp.pop_back ();}}    ;


[C + +] leetcode:83 combinations (backtracking method)

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.