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].
class Solution { public: vector<vector<int> > ans; void dfs(vector<int> &num,vector<int> &path){ if (path.size() == num.size()){ ans.push_back(path); return; } for(int j = 0; j < num.size(); j++){ int ok = 1; for(int i = 0; i < path.size(); i++){ if (path[i] == num[j]){ ok = 0; break; } } if (!ok){ continue; } path.push_back(num[j]); dfs(num,path); path.resize(path.size() -1); } } vector<vector<int> > permute(vector<int> &num) { // Start typing your C/C++ solution below // DO NOT write int main() function ans.clear(); vector<int> path; sort(num.begin(),num.end()); dfs(num,path); return ans; } };
浙公网安备 33010602011771号