Given a collection of distinct 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], [3,2,1]]answer:class Solution {public: vector<vector<int>> permute(vector<int>& nums) { int length = nums.size(); vector<vector<int>> result1,result2; vector<int> temp; result1.push_back(temp); bool flag = false; for(int i = 0; i < length; i ++){ for(int k = 0;k < length; k ++){ for(int j = 0; j < result1.size(); j ++){ flag = false; temp = result1[j]; for(int l = 0; l < temp.size(); l ++){ if(temp[l] == nums[k]){ flag = true; break; } } if(flag) continue; temp.push_back(nums[k]); result2.push_back(temp); temp.pop_back(); } } result1 = result2; result2.clear(); } return result1; } };
新闻热点
疑难解答