Skip to content

Instantly share code, notes, and snippets.

@pdu
Created February 17, 2013 15:30
Show Gist options
  • Select an option

  • Save pdu/4971894 to your computer and use it in GitHub Desktop.

Select an option

Save pdu/4971894 to your computer and use it in GitHub Desktop.
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]. http://leetcode.com/onlinejudge#question_46
class Solution {
public:
vector<vector<int> > permute(vector<int> &num) {
vector< vector<int> > ans;
ans.push_back(num);
vector<int> id(num.size());
for (int i = 0; i < id.size(); ++i)
id[i] = i;
while (next_permutation(id.begin(), id.end())) {
vector<int> tmp;
for (int i = 0; i < id.size(); ++i)
tmp.push_back(num[id[i]]);
ans.push_back(tmp);
}
return ans;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment