码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode: Combination Sum

时间:2015-04-22 10:50:41      阅读:125      评论:0      收藏:0      [点我收藏+]

标签:

Title: 

Given a set of candidate numbers (C) 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.
  • Elements in a combination (a1, a2, … , ak) must be in non-descending order. (ie, a1 ≤ a2 ≤ … ≤ ak).
  • 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] 

思路:基本是DFS的思想。将数组排序之后,每次对当前的这个元素与target比较,看最多能塞进去几个当前的这个元素。

如果数组有相同元素,可以采用注释掉的语句进行去重,或者在递归函数中去重。不去重也不会影响结果。

for (int i = (target / candidates[idx]); i >= 0; i--) {
            record.push_back(candidates[idx]);
}
用来计算最多压入几个当前元素。
for (int i = (target / candidates[idx]); i >= 0; i--) {
            record.pop_back();
            searchAns(ans, record, candidates, target - i * candidates[idx], idx + 1,candidates[idx]);
            //record.pop_back();
       }
弹出栈,再进入递归函数。注意,有可能这个元素就不要压入,所以是i >=0
class Solution {
public:
    vector<vector<int> > combinationSum(vector<int> &candidates, int target) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        sort(candidates.begin(), candidates.end());
        /*vector<int>::iterator pos = unique(candidates.begin(), candidates.end());
        candidates.erase(pos, candidates.end());*/
        vector<vector<int> > ans;
        vector<int> record;
        searchAns(ans, record, candidates, target, 0,-1);
        return ans;
    }

private:
    void searchAns(vector<vector<int> > &ans, vector<int> &record, vector<int> &candidates, int target, int idx, int preValue) {
        if (target == 0) {
            ans.push_back(record);
            return;
        }
        if (  idx == candidates.size() || candidates[idx] > target || preValue == candidates[idx]) {
            return;
        }
        for (int i = (target / candidates[idx]); i >= 0; i--) {
            record.push_back(candidates[idx]);
        }
        for (int i = (target / candidates[idx]); i >= 0; i--) {
            record.pop_back();
            searchAns(ans, record, candidates, target - i * candidates[idx], idx + 1,candidates[idx]);
            //record.pop_back();
        }
    }
};

 

LeetCode: Combination Sum

标签:

原文地址:http://www.cnblogs.com/yxzfscg/p/4446513.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!