第七周LeetCode算法题一道

来源:互联网 发布:mac读取移动硬盘 编辑:程序博客网 时间:2024/06/03 17:56

题目名称:39. Combination Sum

题目难度:Medium

题目描述: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]]

题目分析:
题目要求我们在给定的数组中找出想加起来等于给定数的集合。给定的数组中的数可以重复利用。
首先最直接能想到的应该就是遍历了,遍历所有可能的情况,找出符合条件的情况。但是这样的遍历代价太大了,即使做出来,这样的算法也毫无意义。那么有没有什么比较高效的算法呢?
可以利用递归。递归的每一层尝试所有情况,并更新target。比如给定的例子,target是7,第一层我们新建四种情况,每种情况都从给定给的数组中拿一个数出来。然后更新target:target -= 该数。当target为0的时候,我们就找到了我们要的集合。另外,当target小于0的时候,说明已经没有找下去的必要了,可以及时剪枝。

最后AC的代码如下:

class Solution {public:    bool isDec(vector<int> v) {        for (int i = 0; i < v.size(); ++i) {            for (int j = i + 1; j < v.size(); ++j) {                if (v[i] > v[j]) {                    return false;                }            }        }        return true;    }    void findAllCom(vector<vector<int> > & result, vector<int> current, vector<int> & candidates, int target) {        if (target == 0) {            if (isDec(current)) {                result.push_back(current);                return;            }        } else if (target < 0) {            return;        } else {            for (int i = 0; i < candidates.size(); ++i) {                vector<int> temp(current);                temp.push_back(candidates[i]);                findAllCom(result, temp, candidates, target - candidates[i]);            }        }    }    vector<vector<int> > combinationSum(vector<int>& candidates, int target) {        vector<vector<int> > result;        vector<int> current;        findAllCom(result, current, candidates, target);        return result;    }};