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]
.
解题思路:
回溯法即可。有一个小技巧,先申请一个vector,长度为nums.size(),然后递归调用时采用按引用传递,减少按值传递的开销。
class Solution { public: vector<vector<int>> permute(vector<int>& nums) { vector<vector<int>> result; int len = nums.size(); if(len==0){ return result; } bool isUse[len]; memset(isUse, 0, sizeof(bool)*len); vector<int> item(len); getPermutations(result, nums, isUse, item, 0); return result; } void getPermutations(vector<vector<int>>& result, vector<int>& nums, bool* isUse, vector<int>& item, int itemLen){ if(itemLen==nums.size()){ result.push_back(item); }else{ for(int i=0; i<nums.size(); i++){ if(!isUse[i]){ isUse[i]=true; item[itemLen] = nums[i]; getPermutations(result, nums, isUse, item, itemLen + 1); isUse[i]=false; } } } } };
原文地址:http://blog.csdn.net/kangrydotnet/article/details/45691783