zoukankan      html  css  js  c++  java
  • 【Lintcode】153.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.

     Example

    Given candidate set [10,1,6,7,2,1,5] and target 8,

    A solution set is:

    [
      [1,7],
      [1,2,5],
      [2,6],
      [1,1,6]
    ]

    题解:

      主要是去重复,多个方法,之前已经介绍过。利用set

    Solution 1 ()

    class Solution {
    public:
        vector<vector<int> > combinationSum2(vector<int> &num, int target) {
            vector<vector<int> > res;
            vector<int> cur;
            sort(num.begin(), num.end());
            dfs(res, cur, num, target, 0);
            
            return res;
        }
        void dfs(vector<vector<int> > &res, vector<int> &cur, vector<int> &num, int target, int pos){
            if (!num.empty() && target == 0) {
                res.push_back(cur);
                return;
            }
            for (int i = pos; i < num.size(); ++i) {
                if(i > pos && num[i] == num[i-1]) {
                    continue;
                }
                if (target - num[i] >= 0) {
                    cur.push_back(num[i]);
                    dfs(res, cur, num, target - num[i], i + 1);
                    cur.pop_back();
                } else {
                    break;
                }
            }
        }
    };
  • 相关阅读:
    idea database testconnection 显示灰色
    idea tomcat热部署
    idea 常见报错问题 记录
    Python-Basis-22th
    Python-Basis-21th
    Python-Basis-20th
    Python-Basis-19th
    Python-Basis-18th
    Python-Basis-17th
    Python-Basis-16th
  • 原文地址:https://www.cnblogs.com/Atanisi/p/6869805.html
Copyright © 2011-2022 走看看