leetcode_40 组合总数II

1. 题意

找到所有可能的组合数,只是不能重复选择同一元素。

组合总数II

2. 题解

2.1 我的解法

在leetcode39的基础上,再加上一个标记数组即可。

class Solution {
public:
    void gen(vector<vector<int>> &res, vector<int>& candidates, vector<int> &vis, 
        vector<int> &seq, int target)
        {
            if (target == 0) {
                res.push_back(seq);
                return ;
            }
            if ( target < 0)
                return;

            int sz = candidates.size();
            for ( int i = 0;i < sz; ++i) {
                
                if (vis[i]) continue;
                if (i && !vis[i - 1] && candidates[i] == candidates[i - 1])
                    continue;
                if ( !seq.empty() && candidates[i] < seq[seq.size() - 1] )
                    continue;
                
                vis[i] = 1;
                seq.push_back(candidates[i]);
                gen(res, candidates, vis, seq, target - candidates[i]);
                vis[i] =  0;
                seq.pop_back();


            }
        }

    vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
        

        vector< vector<int> > ans;
        vector<int> seq;
        vector<int> vis(candidates.size(), 0);

        sort(candidates.begin(), candidates.end());

        gen(ans, candidates, vis, seq, target);
        
        return ans;
    }
};
2.2 另一种可能的解法

其实不需要标记数组,根据有序数组的特点和begin来进行去重。

class Solution {
public:
    void gen(vector<vector<int>> &res, vector<int>& candidates, 
        vector<int> &seq, int begin, int target)
        {
            if (target == 0) {
                res.push_back(seq);
                return ;
            }
            if ( target < 0)
                return;

            int sz = candidates.size();
            for ( int i = begin;i < sz; ++i) {
                
                if ( i > begin && candidates[i] == candidates[i - 1])
                    continue;

                seq.push_back(candidates[i]);
                gen(res, candidates, seq, i + 1,target - candidates[i]);
                seq.pop_back();


            }
        }

    vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
        

        vector< vector<int> > ans;
        vector<int> seq;
        vector<int> vis(candidates.size(), 0);

        sort(candidates.begin(), candidates.end());

        gen(ans, candidates,  seq, 0 ,target);
        
        return ans;
    }
};

你可能感兴趣的:(leetcode,回溯,leetcode,算法,职场和发展)