Skip to content

LeetCode 46. 全排列

作者:Choi Yang
更新于:6 个月前
字数统计:394 字
阅读时长:2 分钟
阅读量:

题目描述

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

示例:

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

来源:力扣(LeetCode)链接:https://leetcode-cn.com/problems/permutations 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

解题思路

序列不重复就很简单了,维护一个 vis数组,不重复取就好了。

javascript
var permute = function (nums) {
  let res = [];
  let vis = {};
  let dfs = (t) => {
    if (t.length == nums.length) {
      res.push(t);
    }
    for (let i = 0; i < nums.length; i++) {
      if (vis[i]) continue;
      vis[i] = true;
      t.push(nums[i]);
      dfs(t.slice());
      t.pop();
      vis[i] = false;
    }
  };
  dfs([]);
  return res;
};
cpp
class Solution {
public:
    vector<vector<int>> permute(vector<int>& nums) {
        vector<vector<int>> res;
        vector<int> vis(nums.size(), 0);
        vector<int> t;
        function<void()> dfs = [&]() {
            if (t.size() == nums.size()) {
                res.push_back(t);
                return;
            }
            for (int i = 0; i < nums.size(); i++) {
                if (vis[i]) continue;
                vis[i] = 1;
                t.push_back(nums[i]);
                dfs();
                t.pop_back();
                vis[i] = 0;
            }
        };
        dfs();
        return res;
    }
};
java
class Solution {
    public List<List<Integer>> permute(int[] nums) {
        List<List<Integer>> res = new ArrayList<>();
        List<Integer> t = new ArrayList<>();
        int[] vis = new int[nums.length];
        dfs(nums, vis, t, res);
        return res;
    }

    private void dfs(int[] nums, int[] vis, List<Integer> t, List<List<Integer>> res) {
        if (t.size() == nums.length) {
            res.add(new ArrayList<>(t));
            return;
        }
        for (int i = 0; i < nums.length; i++) {
            if (vis[i] == 1) continue;
            vis[i] = 1;
            t.add(nums[i]);
            dfs(nums, vis, t, res);
            t.remove(t.size() - 1);
            vis[i] = 0;
        }
    }
}
python
class Solution:
    def permute(self, nums: List[int]) -> List[List[int]]:
        res = []
        vis = [0] * len(nums)
        def dfs(t):
            if len(t) == len(nums):
                res.append(t[:])
                return
            for i in range(len(nums)):
                if vis[i]: continue
                vis[i] = 1
                t.append(nums[i])
                dfs(t)
                t.pop()
                vis[i] = 0
        dfs([])
        return res
javascript
学如逆水行舟,不进则退

Contributors

Choi Yang