Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/algorithm/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Algorithm 长度为n的字符串的所有子序列_Algorithm - Fatal编程技术网

Algorithm 长度为n的字符串的所有子序列

Algorithm 长度为n的字符串的所有子序列,algorithm,Algorithm,给定长度为“n”的字符串。如何获得长度为r的所有子序列(r查看所有可能的子序列(连续序列)和通常的子序列(不一定连续)之间的差异很重要 如果这是真的,那么你被问到的问题被称为,最好先估计一下你给出了多少个字符串的长度和子序列的大小 递归算法是这里最好的方法:它允许您将子序列的长度作为一个变量来计算。您将在这里找到一个完美的答案。尝试以下代码(没有伪代码,但我希望可以理解): #包括 #包括 #包括 #包括 #包括 #包括 使用名称空间std; 字符串S; int n; 向量L; void F(整

给定长度为“n”的字符串。如何获得长度为r的所有子序列(r查看所有可能的子序列(连续序列)和通常的子序列(不一定连续)之间的差异很重要

如果这是真的,那么你被问到的问题被称为,最好先估计一下你给出了多少个字符串的长度和子序列的大小

递归算法是这里最好的方法:它允许您将子序列的长度作为一个变量来计算。您将在这里找到一个完美的答案。

尝试以下代码(没有伪代码,但我希望可以理解):

#包括
#包括
#包括
#包括
#包括
#包括
使用名称空间std;
字符串S;
int n;
向量L;
void F(整数索引、整数长度、字符串str)
{
如果(长度==0){
L.推回(str);
}否则{
for(int i=索引;i公共静态无效组合(字符串后缀、字符串前缀){

如果(prefix.length()带有循环?只有
n-r+1
这样的子序列。连续或非连续的子序列?我的意思是所有npr排列。npr=是,包含npr no字符串的列表应该是输出。我不会说递归算法是“最好的”方法;这可能是最明显的。如果字符串很长,则递归方法将导致堆栈溢出。@OliCharlesworth这是每个递归算法的常见缺点,而不是此算法的常见缺点,顺便说一句,此站点的名称证实了这一点:-)在我看来,递归算法是找到问题解决方案的良好起点。在找到递归解决方案后,它总是可以转化为迭代解决方案(如果出于任何原因需要)@ChristianAmmer根据我的工作面试经验,他们经常问一些问题,这些问题意味着首先推导递归算法,然后讨论其优缺点,并根据要求将其转换为迭代算法。
#include <iostream>
#include <cstdio>
#include <string>
#include <cstring>
#include <vector>
#include <algorithm>
using namespace std;

string S;
int n;
vector<string> L;


void F(int index, int length, string str)
{
  if (length == 0) {
    L.push_back(str);
  } else {
    for (int i = index; i < n; i++) {
      string temp = str;
      temp += S[i];
      F(i + 1, length - 1, temp);
    }
  }
}

int main()
{
  S = "abcde"; // replace with your string
  n = S.length();
  int k = 3; // or what you want
  F(0, k, string(""));

  int count = 0;

  for (int i = 0; i < int(L.size()); i++) {
    string temp = L[i];
    sort(temp.begin(), temp.end());
    do {
      cout << temp << endl;
      count++;
    } while (next_permutation(temp.begin(), temp.end()));
  }


  cout << endl << "count = " << count << endl;
  return 0;
}
    public static void combinations(String suffix,String prefix){
            if(prefix.length()<0)
                      return;
            System.out.println(suffix);
            for(int i=0;i<prefix.length();i++) {
                 combinations(suffix+prefix.charAt(i),prefix.substring(i+1,prefix.length()));
        }
    }


//call above function like: combinations("","abcd");