题目描述:

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的组合(不能重复),每个数字能多次使用。

解题思路:

这题我想的是用递归函数将所有情况都试一遍。

代码:

 1 class Solution {
 2 public:
 3     vector<vector<int>> res;
 4     void selectAll(vector<int>& candidates, vector<int> nums, int target, int index){
 5      //candidates为题目所给数组,nums是进行存储数组,target是目标数字(每一层都会变),index是记录上一层nums存储的数字在candidates中的位置(防止重复一维数组出现)
 6         if(target == 0){
 7         //target为0时存一维数组,小于0结束
 8             res.push_back(nums);
 9         }
10         else if(target > 0){
11             int n = candidates.size();
12             for(int i = index; i < n; i++){
13             //进行每一层每种情况的遍历
14                 vector<int> tempNums(nums);
15                 tempNums.push_back(candidates[i]);
16                 selectAll(candidates, tempNums, target-candidates[i], i);
17             }
18         }
19     }
20     vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
21         vector<int> nums;
22         selectAll(candidates, nums, target, 0);
23         return res;
24     }
25 };

 

 

 

posted on 2018-02-28 23:57  宵夜在哪  阅读(93)  评论(0编辑  收藏  举报