Leetcode Note: Combination Sum III

Source: Internet
Author: User

I. Title Description

Find all possible combinations of k numbers this add up to a number n, given this only numbers from 1 to 9 can be used and Each combination should is a unique set of numbers.

Ensure that numbers within the set is sorted in ascending order.

Example 1:
Input:k = 3, n = 7
Output:

[[1,2,4]]

Example 2:
Input:k = 3, n = 9
Output:

[[1,2,6], [1,3,5], [2,3,4]]

Two. Topic analysis

This problem is a combination of the series and the third problem, with the previous two combination Sum combination of the first two questions of the link is relatively close, the change is not big, and this is the most significant difference is that the problem requires a solution of the number of elements of K.

In fact, the problem is combination sum and combination sum II of the complex, the two are mixed together is the solution of the problem. n is the sum of k numbers, if n<0, then directly return, if n = = 0, and at this time the temporary combination of the number of numbers in the temp is exactly k, indicating that at this time is a suitable combination of solutions, will be stored in the result results.

Three. Sample code

#include <iostream>#include <vector>using namespace STD;classSolution { Public: vector<vector<int> >COMBINATIONSUM3 (intKintN) { vector<vector<int> >Result vector<int>Temp Combinationsum3dfs (k, N,1, temp, result);returnResult }Private:voidCombinationsum3dfs (intKintNintLevel vector<int>&temp, vector<vector<int> >&result) {if(N <0)return;if(n = =0&& temp.size () = = k) result.push_back (temp); for(inti = level; I <=9;            ++i) {temp.push_back (i); Combinationsum3dfs (k, n-i, i +1, temp, result);        Temp.pop_back (); }    }};

Four. Summary

The combination sum series is a classic Dfs topic that needs to be studied in depth.

Leetcode Note: Combination Sum III

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.