我基本上要创建的字符串,它由三个操作符号(例如: + - *
或 ++ /
或 +++
)。这些字符串中的每一个应该被推入矢量<串GT; opPermutations
这是我的code到目前为止:
I basically want to create strings that consist of three operation symbols (eg: +-*
or ++/
or +++
). Each one of these strings should be pushed into vector <string> opPermutations
This is my code so far:
// Set up permutations for operators
string operatorBank[4] = {"+","-","*","/"};
do {
string currentPerm = operatorBank[0] + operatorBank[1] + operatorBank[2] + operatorBank[3];
this -> opPermutations.push_back(currentPerm);
} while ( std::next_permutation(operatorBank, operatorBank + 4) );
这被推入载体(字符串)的排列是:
The permutations that are pushed into the vector (as strings) are:
+-*/
+-/*
+/*-
+/-*
-*+/
-*/+
-+*/
-+/*
-/*+
-/+*
/*+-
/*-+
/+*-
/+-*
/-*+
/-+*
我要的不过是让我的排列存在这样的:
What I want however is to have my permutations exist like this:
在每个时间应当在三个字符 在每一个可能的排列,包括那些在其中一个字符重复超过一次,必须是present。我希望它被组织成这样的:
I want it to be organized as such:
+++
---
***
///
/*/
+-+
++*
**/
etc...
我怎样才能做到这一点?
How can I achieve this?
使用递归来打印你的要求。它适应店内置换字符串中的载体应该是微不足道的。我不是一个C ++程序员,所以有可能是更好的方法来做到这一点在C ++中。但这里的主要思想是使用递归。
Using the recursion to print what you asked. Adapting it to store permutation string in vectors should be trivial. I am not a c++ programmer,so there may be better way to do it in C++. but the main idea here is to use recursion.
#include <iostream>
#include <string>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
void displayPermutation(string permutation[], int length){
int i;
for (i=0;i<length;i++){
cout<<permutation[i];
}
cout << endl;
}
void getPermutations(string operatorBank[], int operatorCount,
string permutation[],int permutationLength, int curIndex){
int i;
//stop recursion condition
if(curIndex == permutationLength){
displayPermutation(permutation,permutationLength);
}
else{
for(i = 0; i < operatorCount; i++){
permutation[curIndex] = operatorBank[i];
getPermutations(operatorBank,operatorCount,permutation,
permutationLength,curIndex+1);
}
}
}
int main ()
{
int operatorCount = 4;
int permutationLength = 3;
string operatorBank[] = {"+","-","*","/"};
string permutation[] = {"","","",""}; //empty string
int curIndex = 0;
getPermutations(operatorBank,operatorCount,permutation,
permutationLength,curIndex);
return 0;
}
输出:
+++
++-
++*
++/
+-+
+--
+-*
+-/
+*+
+*-
+**
+*/
+/+
+/-
+/*
+//
.
.
and so on.
下一篇:线性排序算法线性、算法