Permutations

Given a collection of numbers, return all possible permutations.

For example,
[1,2,3] have the following permutations:
[1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], and [3,2,1].

C++:
01 void swap(vector<int>& num, int a, int b)
02 {
03     int tmp=num[a];
04     num[a]=num[b];
05     num[b]=tmp;
06 }
07 
08 void permutation(vector<vector<int> >&result,
09                  vector<int> &num, int pos, int n)
10 {
11     if(pos==n1){
12         result.push_back(num);
13     }else{
14         for(int i=pos;i<n;i++){
15             swap(num,pos,i);
16             permutation(result,num,pos+1,n);
17             swap(num,pos,i);
18         }
19     }
20 }
21 
22  vector<vector<int> > permute(vector<int> &num)
23  {
24      int n=num.size();
25     vector<vector<int> >result;
26     if(n==0)
27         return result;
28     int start=0;
29     int end=n;
30     permutation(result,num,start,end);
31 }
Advertisements
This entry was posted in Array and linked list, Dynamic programming. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s