1. 程式人生 > >【Leetcode】46. Permutations(全排列)

【Leetcode】46. Permutations(全排列)

out wap rem vat int ati swa problems pub

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 };

【Leetcode】46. Permutations(全排列)