zoukankan      html  css  js  c++  java
  • 39. Combination Sum

    Given a set of candidate numbers (C) (without duplicates) 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.

    • All numbers (including target) will be positive integers.
    • 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]
    ]

    题意:输出能加起来等于target的全部组合。
    思路:先排序,递归求所有数字的集合,并判断加起来是否等于target

    class Solution {
    public:
        //先构建递归函数
        void CombinationSumCore(const vector<int>& candidates,vector<vector<int>>& res,vector<int>& com,int target,int pos){
            if(target==0){   //全是正数,结果不可能是0
                res.push_back(com);
                return;
            }
            for(int i=pos;i<candidates.size();i++){
                if(candidates[i]>target)break;   //如果这个数太大了就放弃。
                com.push_back(candidates[i]);    
                CombinationSumCore(candidates,res,com,target-candidates[i],i);  //递归(每加入一个数,target就变小一点。)
                com.pop_back(); //跳过当前的数,并计算下一个数
            }
        }
        vector<vector<int>> combinationSum(vector<int>& candidates, int target){
            sort(candidates.begin(),candidates.end());   //排序
            vector<vector<int>> res;   //存放结果
            vector<int> com;    //存放正在计算的数的集合
            CombinationSumCore(candidates,res,com,target,0);
            return res;
        }
    };
  • 相关阅读:
    类似吸顶功能解决ios不能实时监听onscroll的触发问题
    js 移动端识别手机号码
    H5输入框实时记录文字个数
    C语言指针和数组
    PHP变量
    PHP 的引用计数基础知识
    PHP提高效率的经验
    JS内置Function对象详解
    Javascript小细节总结
    浅析C++中内存分配的方式
  • 原文地址:https://www.cnblogs.com/hozhangel/p/7861447.html
Copyright © 2011-2022 走看看