[LeetCode] Permutations
来源:互联网 发布:动力学分析软件 编辑:程序博客网 时间:2024/05/16 16:59
问题:
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]
.
分析:
这道题的一个assumption是,没有重复的元素。那么方法就是:对于第一个元素,跟每一个元素交换位置(包括自己),然后recursively推进到下一个元素,到最后的时候,形成一种新的permutation,把它push到result里面。如图:
代码(O(n)):
class Solution {public:vector<vector<int> > permute(vector<int> &num) {vector<vector<int> > result;if (num.size() == 0)return result;permuteHelper(num, result, 0);return result;}void permuteHelper(vector<int> &num, vector<vector<int> > & result, int index) {if (index == num.size()) {result.push_back(num);return;}for (int i = index; i < num.size(); i ++) {int temp = num[i];num[i] = num[index];num[index] = temp;permuteHelper(num, result, index + 1);num[index] = num[i];num[i] = temp;}}};
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
- SQL 查询本月无数据用上个月的数据
- 蓝桥杯【入门训练】 Fibonacci数列
- VS2013下cocos2dx3.0alpha1新工程创建
- hadoop-入门
- php main 与 iframe 相互通讯类(同域/跨域)
- [LeetCode] Permutations
- get COM interface method address .
- 【Java.Web】创建一个简单的Java Web项目
- [LeetCode] Permutations II
- AS函数复习
- 直接插入排序
- c# 异常找不到源代码的情况
- [cocos2dx]随机数的使用
- 模拟器设计--未完待续