本文主要是介绍LeetCode 46. Permutations DFS,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
https://leetcode.com/problems/permutations/
这道题没啥说的 暴力DFS搞,也可以next_permutation
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <iostream>
#include <vector>using namespace std;const int SIZE = 1000+1;class Solution {
public:vector< vector<int> > permute(vector<int>& nums) {vector< vector<int> > ret;if(nums.size() == 0) return ret;for(int i=0; i<nums.size(); i++)vis[i] = false;vector <int> gm;dfs(nums, gm, ret);return ret;}void dfs(vector <int> &nums, vector <int> gm, vector< vector<int> > &ret ) {if(gm.size() == nums.size()) {ret.push_back(gm);return ;}for(int i=0;i<nums.size();i++) {if( !vis[i] ) {vis[i] = 1;vector <int> gt(gm);gt.push_back(nums[i]);dfs(nums,gt,ret);vis[i] = 0;}}}private:bool vis[SIZE];
};int main() {//freopen("46.txt", "r", stdin);int n, in;while( cin >> n ) {vector <int> ivec;for(int i=0;i<n; i++) {cin >> in;ivec.push_back(in);}Solution s;vector< vector<int> > ans = s.permute(ivec);cout << "ans.size()" << ans.size() << endl;for(int i=0;i<ans.size();i++) {for(int j=0;j<ans[i].size();j++) {cout << ans[i][j] << ", " ;}cout << endl;}}return 0;
}
这篇关于LeetCode 46. Permutations DFS的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!