Permutations
2015-10-13 02:20
253 查看
Given a collection of numbers, return all possible permutations.
For example,
Analyse:
(1) Swap the 1st element with all the elements, including itself.
(2) Then the 1st element is fixed, go to the next element.
(3) Until the last element is fixed. Output.
new version:
Runtime: 16ms
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].
Analyse:
(1) Swap the 1st element with all the elements, including itself.
(2) Then the 1st element is fixed, go to the next element.
(3) Until the last element is fixed. Output.
new version:
class Solution { public: //swap the first number with every number in the nums vector //then fixed the new first number, and do the same process for the remaining numbers //after reaching (nums.size() - 1)'s depth, push the vector into result //then swap the two number back (backtracking to the original state) vector<vector<int>> permute(vector<int>& nums) { vector<vector<int> > result; if(nums.empty()) return result; helper(result, nums, 0); return result; } void helper(vector<vector<int> >& result, vector<int>& nums, int depth){ if(depth == nums.size() - 1){ result.push_back(nums); return; } for(int i = depth; i < nums.size(); i++){ swap(nums[i], nums[depth]); helper(result, nums, depth + 1); swap(nums[i], nums[depth]); } } };
Runtime: 16ms
class Solution { public: vector<vector<int>> permute(vector<int>& nums) { vector<vector<int> > result; if(nums.empty()) return result; helper(result, nums, 0, nums.size() - 1); return result; } void helper(vector<vector<int> >& result, vector<int> nums, int depth, int n){ if(depth == n){ result.push_back(nums); return; } for(int i = depth; i < nums.size(); i++){ swap(nums[depth], nums[i]); helper(result, nums, depth + 1, n); swap(nums[depth], nums[i]); } } };
相关文章推荐
- 一键获取隐藏Wi-Fi SSID:利用Python和Scapy发现隐藏无线热点
- Nim Game
- bootstrap-switch.js,让checkbox美起来
- 了解Promise Angular(转)
- 新的开始——写给自己的话
- PD中将Comment 从Name复制值
- XMPPFramework框架的导入
- Hexo中如何用Markdown插入本地图片
- 写在开发前——android各种准备工作
- javascript base库
- 支付宝Cookie高危漏洞引发的思考
- WDCP安装并配置php5.4和mongodb
- ARM汇编编程概述
- HDU 5500 Reorder the Books
- (程序员内在修炼)《熔炉》观后感:承认并且面对生活的丑陋面
- Promise/deferred(转)
- 五个解决方案让MongoDB拥有RDBMS的鲁棒性事务
- Foundation Kit框架概叙
- 初步18-画星星
- 解决安装Oracle12c时中文方块字