题解 | #没有重复项数字的全排列#
没有重复项数字的全排列
https://www.nowcoder.com/practice/4bcf3081067a4d028f95acee3ddcd2b1
#include <iostream> #include <algorithm> #include <vector> #include <cmath> using namespace std; bool cmp(int a, int b) { return a < b; } //class Solution { //public: void recursion(vector<vector<int>> &res,vector<int> &num,int index) { if (index == num.size() - 1) {//递归结束:到达最后一个元素,当前排序加入结果集 res.push_back(num); } for (int i = index; i < num.size(); i++) {//遍历从本元素开始的后续元素 swap(num[i], num[index]);//逐个与之交换位置 recursion(res, num, index + 1);//继续往后找 swap(num[i], num[index]);//交换回原来的情况 } } vector<vector<int> > permute(vector<int>& num) { sort(num.begin(), num.end()); vector<vector<int>> res; recursion(res, num, 0); return res; } int main() { vector<int> num; int temp; while (cin >> temp) { num.push_back(temp); if (cin.get() == '\n') break; } vector<vector<int>> end = permute(num); int i = 0; while (!end.empty()) { for (int j = 0; j < end[i].size(); j++) { cout << end[i][j] << ','; } i++; cout << ' '; } return 1; } //};