组合和计算问题

时间:2015-11-19 23:52:59

标签: c++ algorithm

处理以下问题并发布代码。令人困惑的是,似乎没有必要检查(!target) && (!need),使用(!target)本身就可以了吗?但是我们如何保证结果中始终存在精确 k个数字?我尝试了一些,但似乎没有&& (!need)的添加条件。如果有人有任何好的想法,那将是伟大的。感谢。

找出所有可能的k个数字组合,它们加起来为n,假设只能使用1到9的数字,并且每个组合应该是一组唯一的数字。

确保集合中的数字按升序排序。

示例1:

输入:k = 3,n = 7

输出:

[[1,2,4]]

示例2:

输入:k = 3,n = 9

输出:

[[1,2,6], [1,3,5], [2,3,4]]

代码,

class Solution {
public:
    std::vector<std::vector<int> > combinationSum3(int k, int n) {
        std::vector<std::vector<int> > res;
        std::vector<int> combination;
        combinationSum3(n, res, combination, 1, k);
        return res;
    }
private:
    void combinationSum3(int target, std::vector<std::vector<int> > &res, std::vector<int> &combination, int begin, int need) {
        if (!target) {
            res.push_back(combination);
            return;
        }
        else if (!need)
            return;
        for (int i = begin; i != 10 && target >= i * need + need * (need - 1) / 2; ++i) {
            combination.push_back(i);
            combinationSum3(target - i, res, combination, i + 1, need - 1);
            combination.pop_back();
        }
    }
};
提前谢谢, 林

1 个答案:

答案 0 :(得分:1)

只有(!target)就足够了,因为条件为target >= i * need + need * (need - 1) / 2target == 0意味着最后一步target == i,也请注意target >= i * need + need * (need - 1) / 2,因此我们可以在need == 1

时声明target == i && target >= i * need + need * (need - 1) / 2
相关问题