[LeetCode] Combination Sum II

Given a collection of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T.

Each number in C may only be used once in the combination.

Note:

  • All numbers (including target) will be positive integers.
  • Elements in a combination (a1, a2, … , ak) must be in non-descending order. (ie, a1 ≤ a2 ≤ … ≤ ak).
  • The solution set must not contain duplicate combinations.

 

For example, given candidate set 10,1,2,7,6,1,5 and target 8
A solution set is: 
[1, 7] 
[1, 2, 5] 
[2, 6] 
[1, 1, 6] 

 

Hide Tags
 Array Backtracking
 
 

思路: 和Combination Sum 相同,唯一的区别,是这里面所有的元素只让使用一次,所以backtrace时,使用i+1作为参数,另外,考虑到可能有重复元素的情况,要对最后的结果去重,

对结果先sort,然后unique,然后erase,达到去重的效果。

        // note: before use unique, sort must called,
        // as unique func can only erase dupicate element when they are adjacent
        sort(m_result.begin(), m_result.end());
        vector<vector<int> >::iterator pos = unique(m_result.begin(), m_result.end());  
        m_result.erase(pos, m_result.end()); 
class Solution
{
    vector<vector<int> > m_result;
    public:

    void dfs(const vector<int> &candidates, int target, vector<int>& array, int start)
    {
        if(target == 0)
        {   
            m_result.push_back(array);
            return;
        }   

        for(size_t i = start; i < candidates.size(); i++)
        {   
            if(target < candidates[i])
                return;
            array.push_back(candidates[i]);
            dfs(candidates, target - candidates[i], array, i + 1); //Combine sum1 使用的是dfs(candicates, target - candidates[i], i)
            array.pop_back();
        }   
    }   

    vector<vector<int> > combinationSum2(vector<int> &candidates, int target)
    {   
        vector<int> array;
        sort(candidates.begin(), candidates.end());
        //vector<int>::iterator pos = unique(candidates.begin(), candidates.end());  
        //candidates.erase(pos, candidates.end()); 
        dfs( candidates, target, array, 0); 

        // note: before use unique, sort must called,
        // as unique func can only erase dupicate element when they are adjacent
        sort(m_result.begin(), m_result.end());
        vector<vector<int> >::iterator pos = unique(m_result.begin(), m_result.end());  
        m_result.erase(pos, m_result.end()); 

        return m_result;
    }
};

 

posted @ 2015-02-10 18:53  穆穆兔兔  阅读(178)  评论(0编辑  收藏  举报