A combinatorial algorithm for strings the implementation of C language strategy _c language

Source: Internet
Author: User
Tags assert

Basic string composition problem

Title: Enter a string that prints all the combinations of characters in the string. For example, if you enter ABC, it has a combination of a, B, C, AB, AC, BC, ABC.

Above we discussed in detail how to use recursive ideas to find the arrangement of strings. Similarly, the subject can also use recursive ideas to find the combination of strings.

Suppose we want to find a combination of M characters in a string of length n. Let's start by scanning the first character of the string. For the first character, we have two choices: the first is to put the character into the mix, then we need to select the m-1 character in the remaining n-1, and the second is not to put the character into the group, and then we need to select the M character in the remaining n-1 characters. Both of these options are easy to implement with recursion. Here is the reference code for this idea:

 #include <iostream> #include <vector> #include <cstring> using
namespace Std;

#include <assert.h> void combination (char *string, int number,vector<char> &result);
 void combination (char *string) {assert (string!= NULL);
 vector<char> result;
 int i, Length = strlen (string);
for (i = 1; I <= length; ++i) combination (string, I, result);
 } void combination (char *string, int number, vector<char> &result) {assert (string!= NULL);
 if (number = = 0) {static int num = 1;

 printf ("cap%d combo \ t", num++);
 Vector<char>::iterator iter = Result.begin ();
 for (; Iter!= result.end (); ++iter) printf ("%c", *iter);
 printf ("\ n");
 if (*string = = ' ") return;
 Result.push_back (*string);
 Combination (string + 1, number-1, result);
 Result.pop_back ();
Combination (string + 1, number, result);
 int main (void) {char str[] = "ABC";
 Combination (str);
return 0; }

Since a combination can be a combination of 1 characters, a character of 2 characters ... All the time to a combination of n characters, so in the function void combination (char* string) We need a For loop. In addition, we use a vector to store the characters that are selected into the combination.
Method Two: Using the bitwise operation to realize the combination

#include <iostream>
using namespace std;

int a[] = {1,3,5,4,6};
Char str[] = "ABCDE";

void Print_subset (int n, int s)
 printf ("{");
 for (int i = 0; i < n; ++i)
 if (s& (1<<i))     //To determine which bits in the binary of S are 1, that is, to fetch a certain
  printf ("%c", Str[i)) ;  or A[i]
 printf ("}\n");

void subset (int n)
 (int i= 0; i < (1<<n); ++i)
 print_subset (n,i);

int main (void)
 subset (5);
 return 0;

Full combination
For example the given string "abc", the whole combination of meaning from 0 elements, 1 elements, all the way up to n elements, introduces the binary procedure. Take the string "abc" as an example:

<---> NULL
001 <---> C
010 <---> b
011 <---> BC
<---> A
<---> ac
<---> AB
<---> ABC

The idea came out, the code is also relatively good to write, share my code:

   * Write A method This returns all subsets of a set */ 
  #include <stdio.h> 
  #include <STDLIB.H&G t; 
  #include <string.h> 
   * identifies subsets through 0 to 2^-1 * 
   * T = (n * 2^n) 
  void Getsubset ( char *str, int len) 
    int i, Max, index, J; 
    max = 1 << len; 
    for (i = 1; i < Max; I + +) { 
      j = i; 
      index = 0; 
      while (j) { 
        if (J & 1) { 
          printf ("%c", Str[index]); 
        J >>= 1; 
        Index + +; 
      printf ("\ n") 
  int main (void) 
    char str[1000]; 
    while (scanf ("%s", str)!= EOF) { 
      getsubset (str, strlen (str)); 
    return 0; 

Select m number from n

Here are two ways: recursion and backtracking

Recursive thinking is as follows, the number of m from the n number, can be decomposed into the following two steps:

    1. Select the largest number from the N number, and then select the number of m-1 in the remaining number of n-1. Until you select a number from N (m-1)
    2. Select the second small number from the N number and repeat the 1 action

The code is as follows:

   * Recursive solution to combinatorial problems 
  /void Combine (int *arr, int n, int m, int *tmp, const int m) 
    int i, J; 
    for (i = n; i >= m; i-) { 
      tmp[m] = i; 
      if (M = = 0) {  ///select M number for 
        (j = 0; J < m; J + +) { 
          printf ("%d", Arr[tmp[j]]); 
        printf ("\ n"); 
      } else { 
        Combine (arr, i-1, M-1, TMP, M); 

in fact, considering the use of DFS, this topic is much simpler, DFS backtracking condition is the size of the temporary array ==k can be, while attaching a leetcode on the topic, with DFS ideas AC

Given two 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:

AC Code

  public class Solution {public 
    static arraylist<arraylist<integer>> combine (int n, int k) { 
      Arraylist<arraylist<integer>> rs = new arraylist<arraylist<integer>> (); 
      arraylist<integer> list = new arraylist<integer> (); 
      DFS (1, k, N, list, RS); 
      return RS; 
    public static void Dfs (int pos, int k, int n, arraylist<integer> list, arraylist<arraylist<integer>> rs) { 
      if (list.size () = = k) { 
        rs.add (new arraylist<integer> (list)); 
      for (int i = pos; I <= n; i + +) { 
        list.add (i); 
        DFS (i + 1, k, N, list, RS); 
        List.remove (List.size ()-1); 

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.