算法描述:
Given a collection of distinct integers, return all possible permutations.
Example:
Input: [1,2,3]Output:[ [1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], [3,2,1]]
解题思路:题目要求解除所有排列,首先想到的是回溯法。这个题目的关键点是去重。
vector> permute(vector & nums) { vector > results; sort(nums.begin(),nums.end()); vector temp; backtrace(nums, results, temp); return results; } void backtrace(vector & nums, vector >& results, vector & temp){ if(temp.size()==nums.size()){ results.push_back(temp); return; } for(int i=0; i < nums.size(); i++){ if(find(temp.begin(),temp.end(),nums[i]) !=temp.end()) continue; temp.push_back(nums[i]); backtrace(nums,results,temp); temp.pop_back(); } }