Leetcode46. Permutations(全排列)
Posted sunbines
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Leetcode46. Permutations(全排列)相关的知识,希望对你有一定的参考价值。
46. Permutations(全排列)
题目:链接
代码一:
class Solution { private: vector<vector<int>> rems; public: vector<vector<int>> permute(vector<int>& nums) { vector<int> out; vector<int> flag(nums.size(), 0); backtracking(nums, 0, out, flag); return rems; } void backtracking(vector<int> &nums, int start, vector<int> &out, vector<int> &flag) { if(start == nums.size()) { rems.push_back(out); return; } for(int i = 0; i < nums.size(); ++i) if(flag[i] == 0) { out.push_back(nums[i]); flag[i] = 1; backtracking(nums, start + 1, out, flag); out.pop_back(); flag[i] = 0; } } };
代码二:
1 class Solution { 2 private: 3 vector<vector<int>> rems; 4 public: 5 vector<vector<int>> permute(vector<int>& nums) 6 { 7 backtracking(nums, 0); 8 return rems; 9 }; 10 11 void backtracking(vector<int> &nums, int end) 12 { 13 if(end == nums.size()) 14 { 15 rems.push_back(nums); 16 return; 17 } 18 for(int i = end; i < nums.size(); ++i) 19 { 20 swap(nums[end], nums[i]); 21 backtracking(nums, end + 1); 22 swap(nums[end], nums[i]); 23 } 24 } 25 };
以上是关于Leetcode46. Permutations(全排列)的主要内容,如果未能解决你的问题,请参考以下文章
leetcode 46-Permutations and 47-Permutations II