Algorithm exercises: combination of permutations and combinations

Source: Internet
Author: User

Problem description

Give a set of different positive integer sequences and a target value, and find out all possible combinations, making all the elements in the composition and the target values. Requirements:

1) The elements in each combination are sorted in ascending order.

2) The output combination does not contain duplicate combinations.

3) integers in the input sequence can be used multiple times.

Example:

Enter {2,3,4,7}with a target value of 7

Output {7},{2,2,3},{3, 4}

Problem analysis

In order for the output elements to be arranged in ascending order, the input sequence can be sorted. Here we use recursive methods to solve this combinatorial problem, that is, the recursive function is called within a typical for statement. The following points need to be noted:

1) record the remaining target value and, only if the value is 0 , the combination is valid.

2) record the current position, because the number in the sequence can be reused, so the next time recursion, you can also start from the current position, which will be reflected in the parameters of the recursive function.

Refer to the Getresultset function in the code implementation.

Scaling issues

What if there might be the same elements in the sequence, and each element can be used at most once? There are two changes compared to the previous question: 1) Each element can be used at most once, and the next recursion cannot start at the current position, but from the next one. 2) because the sequence contains equal elements, even if each element is used at most one time, duplicate combinations may occur, so in order to avoid repetition, only the first identical element is taken.

Refer to the Getresultsetex function in the code implementation.

Code implementation
#include <iostream> #include <vector> #include <algorithm>using namespace Std;typedef vector<int > intarray; Result set typedef vector<vector<int>> RESULTSET; ResultSet gresultset;//original sequence does not contain the same value void Getresultset (const intarray& msrcarray, int ntarget, intarray& Mdstarra Y, int iStart) {if (Ntarget < 0) return;if (ntarget = = 0) {//Find a result gresultset.push_back (Mdstarray);} else{for (int i = IStart; I < msrcarray.size (); ++i) {//After larger number cannot be satisfied if (Msrcarray[i] > Ntarget) break;//join current element MDS Tarray.push_back (Msrcarray[i]);//recursive processing, because the elements can be reused, so from the current position to continue recursion Getresultset (Msrcarray, Ntarget-msrcarray[i], Mdstarray, I);//reset Mdstarray.pop_back ();}}} There may be the same elements in the sequence, and each element can be used at most once, with no repeating combination of void Getresultsetex (const intarray& msrcarray, int ntarget, intarray& Mdstarray, int iStart) {if (Ntarget < 0) return;if (ntarget = 0) {//Find a result gresultset.push_back (Mdstarray);} else{for (int i = IStart; I < msrcarray.size (); ++i) {///After larger number cannot satisfy the condition if (MSRcarray[i] > Ntarget) break;//Avoid duplicate result sets, take only the first same value into the result if (i! = IStart && Msrcarray[i] = = Msrcarray[i-1]) contin ue;//joins the current element Mdstarray.push_back (Msrcarray[i]),////recursion, because the element can be reused, so recursively//getresultset from the current position (Msrcarray, Ntarget-msrcarray[i], Mdstarray, i);//recursive processing, because the element can not be reused, so continue from the next position recursive Getresultsetex (Msrcarray, Ntarget-msrcarray[i], Mdstarray, i+1);//reset Mdstarray.pop_back ();}}} Output result set void Outputresultset () {if (Gresultset.size () <=) {for (Resultset::iterator it = Gresultset.begin (); it! = GR Esultset.end (); ++it) {for (Intarray::iterator ittemp = It->begin (); Ittemp! = It->end (); ++ittemp) {cout << *ittemp << " ";} cout << Endl;}} cout << Total Results: << gresultset.size () << endl;cout << "--------------------------------------- "<< Endl;} int main () {intarray Msrcarray;intarray mdstarraytemp;int ntarget = 0;while (True) {//construct source data int ntemp = 0;msrcarray.clear () while (CIN >> ntemp) {if (ntemp = = 0) break;msrcarray.push_baCK (ntemp);} CIN >> ntarget;//from small to large sort (msrcarray.begin (), Msrcarray.end ()); Mdstarraytemp.clear (); Gresultset.clear ();// Getresultset (Msrcarray, Ntarget, mdstarraytemp, 0); Getresultsetex (Msrcarray, Ntarget, mdstarraytemp, 0);//output result Outputresultset ();} return 0;}



Series Article Description:
1. This series of articles [algorithmic exercises] is just a record of my learning process and self-motivated, and there is no didactic meaning. It is my pleasure to bring a little knowledge and sentiment to the reader.
2. This series of articles is I learn contacts teacher "into Silicon Valley, programmer interview Secret" a book and write some experience, the majority of the article views from this book, hereby explain!
3. In the article, there are inevitably many errors and shortcomings, welcome readers to criticize, thank you.


Hill son
Reprint Please indicate the source, thank you. Original address:http://blog.csdn.net/s634772208/article/details/46710405


Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Algorithm exercises: combination of permutations and combinations

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.