[LeetCode] (medium) 46. Permutations

https://leetcode.com/problems/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]
]

dfs和递归的逻辑本身是很直观的,难点在于如何组织每一个中间结果使得确定每一位数字的过程尽量简单。我一开始想的是使用下标的映射关系表,可以直接确定某一位是否已经被使用,但是在判断递归终止(或深搜终止)时有困难。

看了别人的答案才发现可以直接使用交换两位这么简单明了的方法,因为遍历交换了所有位置的值,所以就等效于遍历了某一位上的数字的所有可能性。

class Solution {
public:
    vector<vector<int>> permute(vector<int>& nums) {
        static int fast_io = []() { std::ios::sync_with_stdio(false); cin.tie(nullptr); return 0; }();
        vector<vector<int>> result;
        dfs(result, nums, 0);
        return result;
    }
    
    void dfs(vector<vector<int>> &result, vector<int>& nums, int begin){
        if(begin == nums.size()-1){
            result.push_back(nums);
        }else{
            for(int i = begin; i < nums.size(); ++i){
                swap(nums[begin], nums[i]);
                dfs(result, nums, begin+1);
                swap(nums[begin], nums[i]);
            }
        }
    }

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值