leetcode编程记录19 #47 Permutations II

leetcode编程记录19 #47 Permutations II

标签(空格分隔): leetcode c++


这道题目是一道可以用递归的思想来解决的排列的问题,题目如下:

Given a collection of numbers that might contain duplicates, return all possible unique permutations.

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

题目分析和理解:主要来说这道题目看起来也不算太难,它要我们根据一个给定的含有重复元素的序列,找出它的所有的排列。因为这里的排列每一种大的情况总是在小的排列的情况上进行的,所以可以通过递归地交换元素的位置,将经过交换的序列传递下去,在移动左边索引的过程中不断地递归交换,最后当达到序列尽头的时候就将经过交换的序列加到最终的结果中,整个过程正好符合了排列总数为n!的阶乘的性质,每次递归n都减小,这里的n就是可以用于循环递归的次数,选取所有未使用过的数用作排列。

代码如下:

class Solution {
public:
    vector<vector<int>> permuteUnique(vector<int>& nums) {
        vector<vector<int>> result;
        int len = nums.size();
        if (len < 1) {return result;}
        sort(nums.begin(), nums.end());
        recursion(result, nums, 0, len - 1);
        return result;
    }
    void recursion(vector<vector<int>>& result, vector<int> choice, int left, int right) {
        if (left == right) {
            result.push_back(choice);
            return;
        }
        for (int i = left; i <= right; i++) {
            if (i != left && choice[i] == choice[left]) continue;
            swap(choice[left], choice[i]);
            recursion(result, choice, left+1, right);
        }
    }

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值