• 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] 

    思路:这道题的思路和Combination Sum差不多,01背包的思想,但是此题有重复元素出现,可想而知,也会有重复的数组出现。故在上题的基础上,修改了一下,如果出现了相同的元素,则我们使用后面一个元素。记得一定要先排序,然后在处理数据。

    class Solution {
    public:
        void resolve(vector<int> &num,int target,int start,int sum,vector<int> &path,vector<vector<int> > &result)
        {
            if(sum>target)
                return;
            if(sum==target)
            {
                result.push_back(path);
                return;
            }
            for(int i=start;i<num.size();i++)
            {
                path.push_back(num[i]);
                resolve(num,target,i+1,sum+num[i],path,result);
                path.pop_back();
                while(i<num.size()-1 && num[i]==num[i+1])
                    i++;
            }
        }
        vector<vector<int> > combinationSum2(vector<int> &num, int target) {
            vector<vector<int> > result;
            vector<int> path;
            result.clear();
            path.clear();
            sort(num.begin(),num.end());
            resolve(num,target,0,0,path,result);
            return result;
        }
    };
  • 相关阅读:
    uva 11729 Commando War
    剑指offer 38 数字在排序数组中出现的次数
    剑指offer 35 第一个只出现一次的字符
    剑指offer 33 把数组排成最小的数
    剑指offer17 合并两个排序的链表
    跳台阶
    app上线
    剑指offer54 表示数值的字符串
    剑指offer49 把字符串转换成整数
    段错误
  • 原文地址:https://www.cnblogs.com/awy-blog/p/3688227.html
Copyright © 2020-2023  润新知