Leetcode216&39

1、Combination Sum III
Find all possible combinations of k numbers that add up to a number n, given that only numbers from 1 to 9 can be used and each combination should be a unique set of numbers.

Example 1:

Input: k = 3, n = 7

Output:

[[1,2,4]]

Example 2:

Input: k = 3, n = 9

Output:

[[1,2,6], [1,3,5], [2,3,4]]
这种题的思路无非就是从头开始,一个个的找,个数和总和都不满足时就添加,从小到大,如果个数和总和有一个“超”了,就删除这个,加入下一个,只有当个数和总和都满足时,才存入。在“超”之前,我们需要递增的就只有需要加入的数字,隐形递增的还有temp的size()。当个数超了或者总和超了(推一下可以发现,如果每次都是从小到大加入元素,如果总和超了,那一定是伴随着个数超了)return,接下来需要删除刚刚添加的元素,然后返回上一层。。。。
由于n和k都是不固定,简单的几层循环是肯定搞不定了,这种情况一般就要用递归。

class Solution {
public:
    vector<vector<int> > combinationSum3(int k, int n) {
        vector<vector<int> > result;
        vector<int> temp;
        combinationSum3DFS(k, n, 1, temp, result);
        return result;
    }

private:
    void combinationSum3DFS(int k, int n, int level, vector<int> &temp, vector<vector<int> > &result) {
        if (n < 0) return;
        if (n == 0 && temp.size() == k) result.push_back(temp);
        for (int i = level; i <= 9; ++i) {
            temp.push_back(i);
            combinationSum3DFS(k, n - i, i + 1, temp, result);
            temp.pop_back();
        }
    }

};

2、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.

Note:
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]
]
这个题如果按照上题思路,就是先排个序,就依然是从小到大一个个加,区别是每组内元素可重复,所以当不“超”时,元素序号不需要递增,一直加下去直到“超”了。

class Solution {
public:
    vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
        vector<vector<int>> result;
        vector<int> temp;
        sort(candidates.begin(),candidates.end());
        function(candidates,temp,result,target,0);
        return result;
    }
    void function(vector<int>& can,vector<int>& temp,vector<vector<int>>& result,int tar,int level){
        if(tar<0) return;
        if(tar==0) result.push_back(temp);
        for(int i=level;i<can.size();i++){
            temp.push_back(can[i]);
            function(can,temp,result,tar-can[i],i);
            temp.pop_back();
        }
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值