zoukankan      html  css  js  c++  java
  • LeetCode 039 Combination Sum

    题目要求:Combination Sum

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

    The same repeated number may be chosen from C unlimited number of times.

    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 2,3,6,7 and target 7
    A solution set is: 
    [7] 
    [2, 2, 3] 

    代码如下:

    class Solution {
    public:
        vector<vector<int> > combinationSum(vector<int> &candidates, int target) {
            // Start typing your C/C++ solution below
            // DO NOT write int main() function
            sort(candidates.begin(), candidates.end());
            vector<int>::iterator pos = unique(candidates.begin(), candidates.end());
            candidates.erase(pos, candidates.end());
            
            vector<vector<int> > ans;
            vector<int> record;
            searchAns(ans, record, candidates, target, 0);
            return ans;
        }
        
    private:
        void searchAns(vector<vector<int> > &ans, vector<int> &record, vector<int> &candidates, int target, int idx) {
            
            if (target == 0) {
                ans.push_back(record);
                return;
            }
            
            if (idx == candidates.size() || candidates[idx] > target) {
                return;
            }
            
            for (int i = target / candidates[idx]; i >= 0; i--) {
                record.push_back(candidates[idx]);            
            }
            
            for (int i = target / candidates[idx]; i >= 0; i--) {
                record.pop_back();
                searchAns(ans, record, candidates, target - i * candidates[idx], idx + 1);            
            }
        }
    };
  • 相关阅读:
    luogu P4342 [IOI1998]Polygon
    luogu P2051 [AHOI2009]中国象棋
    luogu P3304 [SDOI2013]直径
    luogu P1776 宝物筛选_NOI导刊2010提高(02)
    luogu P2900 [USACO08MAR]土地征用Land Acquisition
    CF1009E [Intercity Travelling]
    luogu P4360 [CEOI2004]锯木厂选址
    luogu P1268 树的重量
    centos7扩展根分区
    tcpdump抓包工具的使用
  • 原文地址:https://www.cnblogs.com/510602159-Yano/p/4279183.html
Copyright © 2011-2022 走看看