题解 | #有重复项数字的全排列#

有重复项数字的全排列

https://www.nowcoder.com/practice/a43a2b986ef34843ac4fdd9159b69863

方法:dfs+递归

与无重复项的数字全排列几乎一样,只是在递归时需要一个条件来判断筛除重复的数字。

时间复杂度:o(n*n!)

空间复杂度:o(n)

class Solution {
  public:
    vector<vector<int> > permuteUnique(vector<int>& num) {
        //将数组排序
        sort(num.begin(), num.end());
        vector<bool> flag(num.size(), false);
        dfs(num, flag, 0);

        return res;
    }

  private:
    vector<vector<int> > res;
    vector<int> temp;

    void dfs(vector<int>& num, vector<bool>& flag, int idx) {
        if (idx == num.size()) {
            res.push_back(temp);
        } else {
            for (int i = 0; i < num.size(); i++) {
                if (flag[i] == false) {
                    //排除重复的数字
                    if (i > 0 && flag[i - 1] == false && num[i - 1] == num[i])
                        continue;
                    flag[i] = true;
                    temp.push_back(num[i]);
                    dfs(num, flag, idx + 1);
                    temp.pop_back();
                    flag[i] = false;
                }
            }
        }
    }
};

刷题题解(c++) 文章被收录于专栏

算法题题解(c++)

全部评论

相关推荐

05-19 19:57
蚌埠学院 Python
2237:Gpa70不算高,建议只写排名,个人技能不在多而在精,缩到8条以内。项目留一个含金量高的,减少间距弄到一页,硕士简历也就一页,本科不要写很多
实习,投递多份简历没人回...
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务