C + + Calculates the number of all combinations of a number

Source: Internet
Author: User

Calculates the combination number of a number and uses recursion to solve it.

If you calculate the number of 3-bit combinations, first select a fixed digit, and then calculate the remaining two-bit combinations, and finally combine them. such as 1 + [23, 32] = 123, 132;

In fixed remaining digits, such as 2 + [13, 31] = 213, 231; 3 + [12, 21] = 312, 321;

The program is divided into two steps, one is to delete an element of any position, one is the number of recursive solution combinations.

More Wonderful content: http://www.bianceng.cnhttp://www.bianceng.cn/Programming/cplus/

Code:

* * * Combination.cpp * * Created on:2014.6.9 * author:spike//*eclipse CDT, gcc 4.8.1*/  
      
#include <iostream> #include <vector> #include <string> using namespace std;  
    void Deleteonenum (std::string& _num, std::size_t _n) {if (_n >= _num.length ()) {return;  
    A String Temp (_num.substr (_n+1));  
_num = _num.substr (0, _n) + temp;  
} void combination (std::string _num, std::string _buff, std::vector<std::string>& _result)  
    {if (_num.length () <= 0) {_result.push_back (_buff);  
        for (std::size_t i=0; I<_num.length (); ++i) {std::string temp (_num);  
        Deleteonenum (temp, i);  
    Combination (temp, _buff+_num[i], _result);  
    int main (void) {std::string num ("4123");  
    std::vector<std::string> result;  
    Combination (num, "", result); for (Std::size_t i=0; I<result.size ();  
    ++i) {std::cout << result[i] << Std::endl;  
return 0; }

Output:

4123  
4132  
4213  
4231  
4312  
4321  
1423 1432 1243 1234 1342 1324  
2413  
2431  
2143  
2134  
2341 2314 3412 3421 3142  
3124  
3241  
3214

Author: csdn Blog spike_king

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.