• 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;
        }
    };
  • 相关阅读:
    uniapp 微信小程序全局分享配置
    友元类
    C++ 关于构造函数和this调用的思考
    opengl 旋转方向
    缓冲区(二)纹理缓冲区+帧缓冲区
    linux 冒号命令,Linux Shell 内建命令:冒号(:)
    cyropto++
    opengl:纹理单元 ( 详解 glUniform1i 和 glGetUniformLocation 的使用)
    git tag
    C++ 友元类
  • 原文地址:https://www.cnblogs.com/hozhangel/p/7861447.html
Copyright © 2020-2023  润新知