1>>> from itertools import permutations
2>>> perms = [''.join(p) for p in permutations('stack')]
3>>> perms
4
1/* to be used something like this:
2int [] toBePermuted = new int [] {1, 2, 3, 4};
3ArrayList<int[]> a = heap(toBePermuted);
4any mention of int [] can be replaced with any other Array of objects */
5
6ArrayList<int []> heap(int [] input) {
7 ArrayList<int []> ret = new ArrayList<int []> ();
8 ret = generate(input.length, input, ret);
9 return ret;
10}
11
12ArrayList<int []> generate(int k, int [] a, ArrayList<int []> output) {
13 if (k == 1) {
14 output.add(a.clone());
15 } else {
16 output = generate(k-1, a, output);
17 for (int i=0; i<k-1; i++) {
18 if (k%2 == 0) {
19 int temp = a[i];
20 a[i] = a[k-1];
21 a[k-1] = temp;
22 } else {
23 int temp = a[0];
24 a[0] = a[k-1];
25 a[k-1] = temp;
26 }
27 generate(k-1, a, output);
28 }
29 }
30 return output;
31}
1void permute(string a, int l, int r)
2{
3 // Base case
4 if (l == r)
5 cout<<a<<endl;
6 else
7 {
8 // Permutations made
9 for (int i = l; i <= r; i++)
10 {
11
12 // Swapping done
13 swap(a[l], a[i]);
14
15 // Recursion called
16 permute(a, l+1, r);
17
18 //backtrack
19 swap(a[l], a[i]);
20 }
21 }
22}
1void perm(char a[], int level){
2
3 static int flag[10] = {0};
4 static char res[10];
5 // If we are the last character of the input string
6 if(a[level] == '\0'){
7 // First we assign stopping point to result
8 res[level] = '\0';
9 // Now we print everything
10 for(int i = 0; res[i] != '\0'; ++i){
11 printf("%c", res[i]);
12 }
13 printf("\n");
14 ++counter;
15 }
16 else{
17 // Scan the original string and flag to see what letters are available
18 for(int i = 0; a[i] != '\0'; ++i){
19 if(flag[i] == 0){
20 res[level] = a[i];
21 flag[i] = 1;
22 perm(a, level + 1);
23 flag[i] = 0;
24 }
25 }
26 }
27}
28
29int main(){
30 char first[] = "abc";
31 perm(first, 0);
32 return 0;
33}
1void permutation(string s)
2{
3 sort(s.begin(),s.end());
4 do{
5 cout << s << " ";
6 }
7 while(next_permutation(s.begin(),s.end()); // std::next_permutation
8
9 cout << endl;
10}
1void find_permutations(vector<int> &array, size_t index, vector<int> current_perm, vector<vector<int>> &res){
2 if(index == array.size())
3 res.push_back(current_perm);
4 else{
5 for(size_t i = 0; i <= current_perm.size(); ++i){
6 vector<int> new_perm(current_perm.begin(), current_perm.end());
7 new_perm.insert(new_perm.begin()+i, array[index]);
8 find_permutations(array, index+1, new_perm, res);
9 }
10 }
11}