LeetCode (Combination Sum)

来源:互联网 发布:js同源策略和跨越请求 编辑:程序博客网 时间:2024/05/20 04:08

Problem:

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]]
Solution:

class Solution {public:    vector<vector<int>> combinationSum(vector<int>& candidates, int target) {        vector<vector<int>> ans;        sort(candidates.begin(), candidates.end());        for (int i = 0; i < candidates.size(); i++){            if (target == candidates[i]){                ans.push_back({target});                break;            }else if (target > candidates[i]){                vector<vector<int>> temp;                temp = combinationSum(candidates, target - candidates[i]);                for (int j = 0; j < temp.size(); j++){                    vector<int> p = temp[j];                    p.push_back(candidates[i]);                    sort(p.begin(), p.end());                    if (find(ans.begin(), ans.end(), p) == ans.end())                        ans.push_back(p);                }            }            else                break;        }        return ans;    }};


0 0
原创粉丝点击