LeetCode 46. Permutations 解题报告
来源:互联网 发布:装修网络平台有哪些 编辑:程序博客网 时间:2024/05/17 08:27
LeetCode 46. Permutations 解题报告
题目描述
Given a collection of distinct numbers, return all possible permutations.
示例
[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]
]
限制条件
没有明确给出。
解题思路
我的思路:
这道题我以前遇到过,所以做的时候没有遇到什么困难。主要思路就是通过递归获得每一个可能的答案,递归过程完成的事情是填充下一个元素到数列中,这一步我们需要标志哪些元素已经放到数列中,哪些还没放。并且要把每一个未放到数列的元素都放一次,然后进行下一次递归。当放入的元素个数等于原始数列的个数就表明找到了一种答案,就可以将这种答案放到结果集中。需要注意的是放了一个元素并且递归后,要还原成放之前的状态才能放下一个元素。
其他思路:
通过之后,在Discuss中看到其他的大神基本都是用递归完成的,而他们的解法与我不同的是,我是填充元素,他们是交换元素。他们的解法核心部分就是将各个位都与后面的每一个位都交换一次,并且这种交换是累积式的,通过自己纸上演算能够体会他们解法的过程。
代码
我的代码
class Solution {private: vector<vector<int>> res; vector<int> origin; int n;public: vector<vector<int>> permute(vector<int>& nums) { n = nums.size(); origin = nums; vector<int> sol; vector<bool> used(n, false); pushElement(sol, used); return res; } void pushElement(vector<int> sol, vector<bool> used) { for (int i = 0; i < n; i++) { if (!used[i]) { sol.push_back(origin[i]); used[i] = true; if (sol.size() == n) { res.push_back(sol); return ; } else { pushElement(sol, used); sol.pop_back(); used[i] = false; } } } }};
其他代码
class Solution {public: vector<vector<int>> permute(vector<int>& nums) { vector<vector<int>> res; permuteRecursive(nums, 0, res); return res; } void permuteRecursive(vector<int> &nums, int begin, vector<vector<int>> & res) { if (begin >= nums.size()) { res.push_back(nums); return ; } for (int i = begin; i < nums.size(); i++) { swap(nums[begin], nums[i]); permuteRecursive(nums, begin + 1, res); swap(nums[begin], nums[i]); } }};
总结
这道题要懂得把置换的过程分解成一步一步的操作,而每一步的操作是类似的,所以可以用递归来实现,而具体递归的过程,就根据自己解法的核心思想而有所不同。
腾出了时间填好今天的坑,明天再继续,这周好忙,不保证每天都能写解题报告,尽量吧。坚持坚持,努力加油~
0 0
- [leetcode] 46. Permutations 解题报告
- LeetCode 46. Permutations 解题报告
- [Leetcode] 46. Permutations 解题报告
- [LeetCode]Permutations,解题报告
- 【LeetCode】Permutations 解题报告
- LeetCode-Permutations-解题报告
- [LeetCode] Permutations 解题报告
- Permutations [Leetcode 解题报告]
- Leetcode # 46. Permutations 全排列 解题报告
- [leetcode]46. Permutations@Java解题报告
- 【LeetCode】Permutations II 解题报告
- [LeetCode] Permutations II 解题报告
- Permutations II [Leetcode 解题报告]
- [leetcode] 47. Permutations II 解题报告
- [Leetcode] 47. Permutations II 解题报告
- [leetcode]47. Permutations II@Java解题报告
- Leetcode #47. Permutations II 全排列2 解题报告
- leetcode 之 Permutations 解题思路
- 二叉树的各种遍历方法
- JavaWeb初级学习 之 JQuery-简介、选择器
- Sum of Two Integers
- mysql desc asc基本命令总结
- 做一个有自我要求的读者
- LeetCode 46. Permutations 解题报告
- Android事件分发<二>
- 学习C语言的一点感受
- win32主程序入口设置
- 剑指offer-包含min函数的栈
- python实现多进程_multiprocessing
- 高数个人资料整理
- Eclipse使用Maven创建Web时错误:Could not resolve archetype org.apache.maven.archetypes:maven-archetype-webap
- Android 实现Viewpager指示器