http://www.geeksforgeeks.org/write-a-c-program-to-print-all-permutations-of-a-given-string/

A permutation, also called an “arrangement number” or “order,” is a rearrangement of the elements of an ordered list S into a one-to-one correspondence with S itself. A string of length n has n! permutation.
Source: Mathword(http://mathworld.wolfram.com/Permutation.html)

Below are the permutations of string ABC.
ABC, ACB, BAC, BCA, CAB, CBA

Here is a solution using backtracking.

NewPermutation

 

//c# code
public
static class Permutation { //static void Main(string[] args) //{ // char[] s = new char[] { 'a', 'b', 'c' }; // Permutation.permutate(ref s, 0, 3); // Console.Read(); //} public static void swap(ref char a, ref char b) { char tmp; tmp = a; a = b; b = tmp; } // 1. String // 2. Starting index of the string // 3. Ending index of the string. */ public static void permutate(ref char[] sArray,int i,int n) { int j = 0; if (i ==n) { Console.WriteLine(sArray); } else { for (j = i; j < n; j++) { Permutation.swap(ref sArray[i],ref sArray[j]); Permutation.permutate(ref sArray, i + 1, n); Permutation.swap(ref sArray[i], ref sArray[j]); } } } }

Algorithm Paradigm: Backtracking
Time Complexity: O(n*n!)

posted on 2013-06-07 16:40  Alan Yang  阅读(476)  评论(0编辑  收藏  举报