题目:
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]
.
代码:
class Solution { public: vector<vector<int>> permute(vector<int>& nums) { vector<vector<int> > ret; vector<int> none; ret.push_back(none); for ( size_t i = 0; i < nums.size(); ++i ){ vector<vector<int> > tmp = ret; ret.clear(); for ( size_t j = 0; j < tmp.size(); ++j ){ for ( size_t k = 0; k < i+1; ++k ){ vector<int> ori = tmp[j]; ori.insert(ori.begin()+k, nums[i]); ret.push_back(ori); } } } return ret; } };
tips:
参考(http://bangbingsyb.blogspot.sg/2014/11/leetcode-permutations-i-ii.html)
采用增量构造法(暴力法解决):每次新增一个元素,对上次已有的permutations,从0到size挨个位置插入一遍。
[] // 注意一开始要给ret一个空的vector<int> 这样才循环才能run起来
[1]
[2 1],[1 2]
[3 2 1], [2 3 1], [2 1 3], [3 1 2 ], [1 3 2], [1 2 3]
时间: 2024-11-09 16:13:16