46. Permutations
来源:互联网 发布:夜景卫星图 知乎 编辑:程序博客网 时间:2024/06/05 00:41
问题描述
Given a collection of distinct 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],
[3,2,1]
]
思路分析
该题给出一组数字,要求写出所有的数字排列方式。我们可以采用递归的方式。设置一个中间位置变量pos,让它初始化为0。用一层循环让该位置的数与其他所有位置的数交换位置,在该循环中进行递归调用,调用时将pos设为pos+1。直至pos的值等于整数向量的size-1即表示完成。
代码展示
#include<iostream>#include<string>#include<vector>using namespace std;class Solution {public: vector<vector<int> > permute(vector<int>& nums) { vector<vector<int> > ret; Helper(ret, nums, 0); return ret; } void Helper(vector<vector<int> >& ret, vector<int> num, int pos) { if(pos == num.size()-1) ret.push_back(num); else { for(int i = pos; i < num.size(); i ++) { swap(num[pos], num[i]); Helper(ret, num, pos+1); swap(num[pos], num[i]); } } }};int main(){ int n; cout<<"请输入向量长度:"; cin>>n; vector<int> nums; int a; for(int i=0;i<n;i++){ cin>>a; nums.push_back(a); } Solution solution; vector<vector<int> > result=solution.permute(nums); int size = result.size(); for(int i=0;i<size;i++){ int size1=result[i].size(); cout<<"["; int j; for(j=0;j<size1-1;j++){ cout<<result[i][j]<<", "; } cout<<result[i][j]<<"]"<<endl; }}
运行结果分析
阅读全文
0 0
- 46. Permutations
- 46. Permutations
- 46. Permutations
- 46. Permutations
- 46. Permutations
- 46. Permutations
- 46. Permutations
- 46. Permutations
- 46. Permutations
- 46. Permutations
- 46. Permutations
- 46. Permutations
- 46. Permutations
- 46. Permutations
- 46. Permutations
- 46. Permutations
- 46. Permutations
- 46. Permutations
- 修改IP地址失败的解决方法
- Java初学的一些笔记
- 数据结构学习记录-树的基本术语
- Redis 发布订阅
- Spring Struts2 Hibernate
- 46. Permutations
- Android逆向之旅---Android手机端破解神器MT的内购VIP功能破解教程
- 二分+SPFA
- 实验吧WEB--简单的sql注入之3
- 在使用EF开发时候,遇到 using语句中使用的类型必须可隐式转换为System.IDisposE
- Oracle多表查询-数据集合操作
- jsp九大内置对象
- HTML响应式web设计(RWD) Bootstrap
- 始于开始,那么也终于结束