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 i, int j)
02 {
03     int t=num[i];
04     num[i]=num[j];
05     num[j]=t;
06 }
07 void permuteHelper(vector<vector<int>>& result, vector<int>& num, int n)
08 {
09     int m=num.size();
10     if(n>=m)
11     {
12         result.push_back(num);
13         return;
14     }
15     for(int i=n;i<m;i++)
16     {
17         swap(num,n,i);
18         permuteHelper(result,num,n+1);
19         swap(num,n,i);
20     }
21 }
22 class Solution {
23 public:
24     vector<vector<int> > permute(vector<int> &num) {
25         // Start typing your C/C++ solution below
26         // DO NOT write int main() function
27         vector<vector<int>> result;
28         permuteHelper(result, num, 0);
29         return result;
30     }
31 };
Advertisements
This entry was posted in Array and linked list, Recursive. 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