[leetcode] 46.Permutations
来源:互联网 发布:excel去重复数据计数 编辑:程序博客网 时间:2024/05/16 04:44
题目: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].
题意是:给一个数字的集合,让你找出所有的排列。
思路:这道题是一个全排列的问题,如果有n个数,会有n * (n-1) * (n-2)…1种排列情况。也就是说第一位上有n种情况,第二位上有n-1种情况,以此类推。也就是说第一位上可以是这n个数里的一个,假如第一位上放的是第i个数,那么第二位上除了第i个数的那n-1个数。
使用回溯的思想,在考虑第k位时,让第k位等于后面这n-k中的任一个,采用交换A[k]与A[j]的方法,让第k位上的数变成第j个数,接着递归在剩下的n-k-1个数中使用全排列。然后再将第k个数与第j个数交换回来。
代码如下:
class Solution {public: vector<vector<int>> permute(vector<int>& nums) { vector<vector<int>> result; if(nums.size() == 0) return result; else if(nums.size() == 1){ result.push_back(nums); return result; } getAllPermutation(result,nums,0); return result; } void getAllPermutation(vector<vector<int>> &result,vector<int> nums,int i){ if(i == nums.size() - 1){ result.push_back(nums); return; } getAllPermutation(result,nums,i+1); for(int j = i + 1; j < nums.size(); j++){ swap(nums[i],nums[j]); getAllPermutation(result,nums,i+1); swap(nums[i],nums[j]); } }};
0 0
- [LeetCode]46.Permutations
- LeetCode 46.Permutations
- 46. Permutations Leetcode Python
- LeetCode --- 46. Permutations
- [Leetcode] 46. Permutations
- [leetcode] 46.Permutations
- LeetCode 46. Permutations DFS
- 46. Permutations LeetCode
- Leetcode 46. Permutations
- leetcode 46. Permutations
- LeetCode *** 46. Permutations
- LeetCode 46. Permutations
- leetcode 46. Permutations
- LeetCode - 46. Permutations
- 【leetcode】46. Permutations
- leetcode 46. Permutations
- [LeetCode] 46. Permutations
- leetcode 46. Permutations
- Uva 12716
- UVa 10564 - Paths through the Hourglass(DP)
- mysql取得数据库所有表名和字段注释
- Spring核心学习(1)实现基本的容器-包括注入和获取功能
- VTK点云的显示
- [leetcode] 46.Permutations
- Mono 4.0 伴随着C# 6发布
- 【转】JAVA设计模式之单例模式
- Android基础之SQLite数据
- 柔性数组
- 后缀数组
- Java 常用类库
- 3--黑马程序员--技术总结之流程控制语句
- C语言宏与单井号(#)和双井号(##)