leetcode-47

https://leetcode-cn.com/problems/permutations-ii/

思路:dfs,46、47和38、39类似

void dfs(vector<int>& nums, vector<int> &temp, int start, vector<vector<int> > &res, vector<int> &used) {
    if (temp.size() >= nums.size()) {
        res.push_back(temp);
        return ;
    }
    for (int i = 0; i < nums.size(); i++) {
        if (used[i] == 0) {
            //去重
            if (i > 0 && used[i - 1] == true && nums[i] == nums[i - 1]) {
                continue;
            }
            temp.push_back(nums[i]);
            used[i] = 1;
            dfs(nums, temp, i + 1, res, used);
            temp.pop_back();
            used[i] = 0;
        }
    }
}

vector<vector<int> > permuteUnique(vector<int>& nums) {
    vector<vector<int> > res;
    if (nums.size() == 0) {
        return res;
    }
    if (nums.size() == 1) {
        res.push_back(nums);
        return res;
    }
    //去重建立在有序数组上
    sort(nums.begin(), nums.end());
    vector<int> temp;
    //标记数组,排列只能使用一次。
    vector<int> used(nums.size(), 0);
    dfs(nums, temp, 0, res, used);
    return res;
}

 

上一篇:C++算法代码——你要乘坐的飞碟在这里[usaco]


下一篇:mxnet基础到提高(47)-RowSparseNDArray