zoukankan      html  css  js  c++  java
  • [Leetcode 52] 39 Combination Sum

    Problem:

    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 (a1a2, � , 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]

    Analysis:

    It's also a backtracking problem. One thing need to be noticed is that [1, 2, 1] and [1, 1, 2] are considered the same sum, so they can't be in the result. Further more, since final results are required to be sorted, [1, 2, 1] is even an invalid result. The solution to this problem is that make sure the given array sorted and bc won't access any element before the element has been accessed. That's why we add pos into the bc function.

    Code:

     1 class Solution {
     2 public:
     3     vector<vector<int> > res;
     4     int tar;
     5 
     6     vector<vector<int> > combinationSum(vector<int> &candidates, int target) {
     7         // Start typing your C/C++ solution below
     8         // DO NOT write int main() function
     9         res.clear();
    10         if (candidates.size() == 0)
    11             return res;
    12             
    13         vector<int> path;
    14         tar = target;
    15         sort(candidates.begin(), candidates.end());
    16         bc(0, path, 0, candidates);
    17         
    18         return res;
    19     }
    20     
    21     
    22     void bc(int sum, vector<int> path, int pos, vector<int> &cand) {
    23         if (sum > tar)
    24             return ;
    25             
    26         if (sum == tar) {
    27             res.push_back(path);
    28         }
    29         
    30         for (int i=pos; i<cand.size(); i++) {
    31             path.push_back(cand[i]);
    32             bc(sum+cand[i], path, i, cand);
    33             path.pop_back();
    34         }
    35         
    36         return ;
    37     }
    38 };
    View Code
  • 相关阅读:
    大数据技术(1-5题)
    如何使用不同的编程语言来造一匹马
    Redis 数据类型及应用场景
    Swoole中内置Http服务器
    redis 数据库主从不一致问题解决方案
    easyswoole对接支付宝,微信支付
    PHP+Swoole 作为网络通信框架
    基于swoole实现多人聊天室
    swoole与php协程实现异步非阻塞IO开发
    swoole中使用task进程异步的处理耗时任务
  • 原文地址:https://www.cnblogs.com/freeneng/p/3099595.html
Copyright © 2011-2022 走看看