46. Permutations

Given a collection of distinct integers, return all possible permutations.

Example:

Input: [1,2,3]
Output:
[
  [1,2,3],
  [1,3,2],
  [2,1,3],
  [2,3,1],
  [3,1,2],
  [3,2,1]
]

 

AC code:

class Solution {
public:
    vector<vector<int>> permute(vector<int>& nums) {
        vector<vector<int>> v;
        iteration(nums, v, 0);
        return v;
    }
    
    void iteration(vector<int>& nums, vector<vector<int>>& v, int begin) {
        if (begin >= nums.size()) {
            v.push_back(nums);
            return;
        }
   
        for (int i = begin; i < nums.size(); ++i) {
            swap(nums[begin], nums[i]);
            iteration(nums, v, begin+1);
            swap(nums[begin], nums[i]);
        }
    }
};

Runtime: 12 ms, faster than 42.11% of C++ online submissions for Permutations.


2021-05-05

给定一个 没有重复 数字的序列,返回其所有可能的全排列。

示例:

输入: [1,2,3]
输出:
[
[1,2,3],
[1,3,2],
[2,1,3],
[2,3,1],
[3,1,2],
[3,2,1]
]

 

思路:回溯法,用到了两个辅助空间,比较容易理解。之前的解法确实很厉害,直接利用交换变量的方法来求解,然后再回溯,不太容易想得到。

Code:

class Solution {
private:
    vector<vector<int> > ans;
    int len;
public:
    void DFS(vector<int>& nums, vector<bool>& visited, vector<int>& temp, int count) {
        if (count == len) {
            ans.push_back(temp);
            return;
        }
        for (int i = 0; i < len; ++i) {
            if (!visited[i]) {
                visited[i] = true;
                temp[count] = nums[i];
                DFS(nums, visited, temp, count+1);
                // 回溯
                visited[i] = false;
            }
        }
    }

    vector<vector<int>> permute(vector<int>& nums) {
        len = nums.size();
        vector<bool> visited(len+1, false);
        vector<int> temp(len);
        DFS(nums, visited, temp, 0);
        return ans;
    }
};    

 

posted @ 2018-10-17 11:50  Veritas_des_Liberty  阅读(182)  评论(0编辑  收藏  举报