[leetcode] Permutations
来源:互联网 发布:被淘宝大学骗了怎么办 编辑:程序博客网 时间:2024/05/22 03:23
From : https://leetcode.com/problems/permutations/
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>> ans; vector<int> cur; vector<bool> notUse(nums.size(), true); insert(ans, cur, nums, notUse, 0); return ans; } void insert(vector<vector<int>>& ans, vector<int>& cur, vector<int>& nums, vector<bool>& notUse, int used) { if(used == nums.size()) {ans.push_back(cur); return; } for(int i=0, len=nums.size(); i<len; i++) { if(notUse[i]) { notUse[i] = false; cur.push_back(nums[i]); insert(ans, cur, nums, notUse, used+1); cur.pop_back(); notUse[i] = true; } } }};
改进:
class Solution {public: vector<vector<int> > permute(vector<int> &num) { vector<vector<int> > ans;dfs(ans, num, 0);return ans; }void dfs(vector<vector<int> >& ans, vector<int>& num, int cur) {if(num.size() == cur) { ans.push_back(num); return; }for(int i = cur; i < num.size(); ++i) {swap(num[cur], num[i]);dfs(ans, num, cur+1);swap(num[cur], num[i]);}}};
0 0
- 【LeetCode】Permutations && Permutations II
- leetcode: Permutations/Permutations II
- leetcode Permutations & Permutations II
- [Leetcode]Permutations && Permutations II
- LeetCode: Permutations
- LeetCode: Permutations
- [Leetcode] Permutations
- [LeetCode] Permutations
- Leetcode: Permutations
- [Leetcode] Permutations
- [Leetcode] Permutations
- [LeetCode]Permutations
- LeetCode-Permutations
- [leetcode] permutations
- LeetCode - Permutations
- Leetcode: Permutations
- 【leetcode】Permutations
- 【LeetCode】Permutations
- 用代码为视图添加约束, VFL语法总结, 网址:www.iphonetrain.com 公司:星宇无限(北京)科技有限公司
- 博客开启
- 添加一个c文件,编译报错
- Linux-FLASH驱动设计二
- Java EE自动提示设置
- [leetcode] Permutations
- PHP运行模式
- C# Dictionary用法总结
- Servlet 初步(五) session
- 8.17
- 认识StringBuffer
- IOS微信音乐播放问题
- 常用排序算法之冒泡排序
- 通信原理课程设计报告