39. Combination Sum

来源:互联网 发布:百科知识竞赛网络宣传 编辑:程序博客网 时间:2024/06/06 10:50

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 (a1a2, … , 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] 

题意:给出一串数和目标值,返回用这些数组成目标值的排列。

思路:回溯。回溯类似于深搜,这条路可以走就走,走不动了改路结束,然后回到上一步的初使状态,去做其他选择。

class Solution {public:vector<vector<int>> combinationSum(vector<int>& candidates, int target) {sort(candidates.begin(), candidates.end());vector<int> cur;vector<vector<int>> res;backtracking(candidates, 0, cur, target, res);return res;}void backtracking(vector<int>& candidates, int level, vector<int>& cur, int target, vector<vector<int>>& res){if (target == 0){res.push_back(cur);return;}for (int i = level; i < candidates.size(); i++){int tmp = candidates[i];if (tmp <= target){cur.push_back(tmp);backtracking(candidates, i, cur, target-tmp, res);cur.pop_back();}}}};






0 0