[LeetCode] 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]
.
思路:回溯法,排序树,题目没有考虑到元素有重复的情况,我再最后加了sort+unique
有关回溯法 子集树和排序树 http://www.cnblogs.com/diegodu/p/3805669.html
class Solution { vector<vector<int> > m_result; public: void swap(int & x, int & y) { int tmp = x; x = y; y = tmp; } void dfs(vector<int> & num, int dep ) { if(dep == num.size()) { m_result.push_back(num); return; } for(int i = dep; i < num.size(); i++) { //if(i != dep && num[i] == num[dep]) // continue; swap(num[i], num[dep]); dfs(num, dep + 1); swap(num[i], num[dep]); } } vector<vector<int> > permute(vector<int> &num) { dfs( num, 0); //erase the duplicate //sort(m_result.begin(), m_result.end()); //m_result.erase(unique(m_result.begin(), m_result.end()), m_result.end()); return m_result; } };
思路2: 从 http://www.cnblogs.com/remlostime/archive/2012/11/13/2767818.html 看来的想法,用canUse标记是否使用,没用才可以用,否则就不能用。
为什么用这个呢?因为这种思路对Permutations II 非常有帮助。
class Solution { private: vector<vector<int> > ret; bool canUse[100]; int a[100]; public: void dfs(int dep, int maxDep, vector<int> &num) { if (dep == maxDep) { vector<int> ans; for(int i = 0; i < maxDep; i++) ans.push_back(a[i]); ret.push_back(ans); return; } for(int i = 0; i < maxDep; i++) if (canUse[i]) { canUse[i] = false; a[dep] = num[i]; dfs(dep + 1, maxDep, num); canUse[i] = true; } } vector<vector<int> > permute(vector<int> &num) { // Start typing your C/C++ solution below // DO NOT write int main() function ret.clear(); memset(canUse, true, sizeof(canUse)); dfs(0, num.size(), num); return ret; } };