[LeetCode] 46. Permutations

题:https://leetcode.com/problems/permutations/description/

题目:

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

For example,
[1,2,3] have the following permutations:

[
  [1,2,3],
  [1,3,2],
  [2,1,3],
  [2,3,1],
  [3,1,2],
  [3,2,1]
]


思路 1

广度遍历,原来一直以为广度遍历是队列,所以只要是函数递归一定是深度遍历,但递归也可用广度,只是广度遍历是在整体生成广度遍历的对象,而具体执行过程还是深度遍历。

Code

class Solution {

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

思路 2

对于生成所有序列,先创建一个空的序列[ [ ] ], 以 遍历数字序列,插入到原来有每个序列中的任何可能位置,*1*2* ,如序列[1,2]中,可以插三个位置,这个就生成了数字序列对应的全部序列,这个和以往生成序列的思维不一样,所以解决方式不一样,显然这种方式更加适合编程的,即计算机的执行过程。

Code Python

class Solution:
    def permute(self, nums):
        perms = [[]]   
        for n in nums:
            new_perms = []
            for perm in perms:
                for i in range(len(perm)+1):   
                    new_perms.append(perm[:i] + [n] + perm[i:])   ###insert n
            perms = new_perms
        return perms





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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值