leetcode 刷题之路 23 Combination Sum

来源:互联网 发布:金山数据恢复大师vip 编辑:程序博客网 时间:2024/06/04 21:53

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] 

给定一个数组和目标数值,从数组中任意取数字求和使得和为目标数值,求数字的所有组合。

采用递归求解,若数字等于target时,分两种情况:

若当前数字参与求和,则已经找到了一种可能的组合,将当前数字加入到temp变量中,并将temp变量加入到最终的返回结果ret中。

若当前数字不参与求和,则target不变,current变量递增,target递减num[current],继续递归调用helper函数进入到数组下一个数字的处理。

若当前数字小于target变量时,分三种情况:

当前数字参与求和运算,记录当前数字到temp中,current递增,target递减num[current],进入数组下一个数字的处理;

当前数字参与求和运算,记录当前数字到temp中,current不变,target递减num[current],再次在当前数字上进行处理。

当前数字不参与求和运算,current递增,target不变,进入数组下一个数字的处理。

若当前数字大于target变量时,只有一种情况,那就是当前数字不参与求和运算,target不变,current递增,调用helper函数进入下一个数字的处理。

当current和数组长度相等时,递归终止,表示求和失败。

根据上面的分析,容易写出以下代码:

测试通过程序:

class Solution {public:vector<vector<int> > combinationSum(vector<int> &num, int target){vector<vector<int>> ret;vector<int> temp;helper(num, ret, temp, 0, target);for (int i = 0; i < ret.size(); i++)sort(ret[i].begin(), ret[i].end());sort(ret.begin(), ret.end());vector<vector<int>>::iterator iter=unique(ret.begin(), ret.end());//unique去除相邻的重复元素ret.erase(iter, ret.end());return ret;}static void helper(vector<int> &num, vector<vector<int>> &ret, vector<int> &temp, int current, int target){if (current == num.size())return;if (target == num[current]){temp.push_back(num[current]);ret.push_back(temp);temp.pop_back();}else if (target>num[current]){temp.push_back(num[current]);helper(num, ret, temp, current+1, target-num[current]);temp.pop_back();temp.push_back(num[current]);helper(num, ret, temp, current, target - num[current]);temp.pop_back();}helper(num, ret, temp, current + 1, target);}};



0 0
原创粉丝点击