标签:style blog class code ext color int 2014 404 cti rgb
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]
.
分析:暂时不用考虑重复元素问题。
思路一:排列问题一般可以用递归进行解决,先从序列中抽出一个数,将其余的树进行排列,然后依次插入得到的排列的位置即可得到结果。如[1, 2, 3]先将1抽出,得到[2, 3]的排列结果:[2, 3] 与 [3, 2], 然后将1插入到[2, 3]以及[3, 2]的各个位置。
class Solution { public: vector<vector<int> > permute(vector<int> &num) { vector<vector<int>> result, real_result; if(num.size() <= 1) { result.push_back(num); return result; } int temp = num[num.size() - 1]; num.pop_back(); result = permute(num); for(auto vi = result.begin(); vi != result.end(); vi++) { for(int i = 0; i <= (*vi).size(); i++) { vector<int> tempV = (*vi); tempV.insert(tempV.begin() + i, temp); real_result.push_back(tempV); } } return real_result; } };
class Solution { public: vector<vector<int> > permute(vector<int> &num) { vector<vector<int> > result; sort(num.begin(), num.end()); do { result.push_back(num); } while(next_permutation(num.begin(), num.end())); return result; } };
【Leetcode】Permutations,码迷,mamicode.com
标签:style blog class code ext color int 2014 404 cti rgb
原文地址:http://blog.csdn.net/lipantechblog/article/details/24790161