LeetCode Logo

46. 全排列

https://leetcode.cn/problems/permutations/description

给定一个不含重复数字的数组 nums ,返回其 所有可能的全排列 。你可以 按任意顺序 返回答案。

示例 1:

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

示例 2:

输入:nums = [0,1]
输出:[[0,1],[1,0]]

示例 3:

输入:nums = [1]
输出:[[1]]

提示:

  • 1 <= nums.length <= 6
  • -10 <= nums[i] <= 10
  • nums 中的所有整数 互不相同

思路:递归+回溯,并用flag数组避免重复访问

C#实现:

public class Solution {
    public IList<IList<int>> Permute(int[] nums) {
        var res = new List<IList<int>>();
        var current = new List<int>();
        bool[] used = new bool[nums.Length];
        Permute(nums, res, current, used);
        return res;
    }

    public void Permute(int[] nums, IList<IList<int>> res, List<int> current, bool[] used) {
        // 若当前排列长度等于数组长度,说明找到一个,创建副本加入res并返回
        if(current.Count() == nums.Length) {
            res.Add(new List<int>(current));
            return;
        }
        for(int i = 0; i < nums.Length; i++) {
            // 若当前数字没被使用
            if(!used[i]) {
                // 选择当前数字
                used[i] = true;
                current.Add(nums[i]);
                // 递归调用
                Permute(nums, res, current, used);
                // 回溯撤销选择
                current.RemoveAt(current.Count() - 1);
                used[i] = false;
            }
        }
    }
}

Subscribe for New Articles!

Leave a Comment

Your email address will not be published. Required fields are marked *