LeetCode:Combination Sum(回溯的经典框架(路径描述))

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

 

 1 class Solution {
 2 public:
 3     vector<vector<int>> combinationSum(vector<int>& nums, int target) {
 4         sort(nums.begin(),nums.end());
 5         vector<vector<int>> result;
 6         vector<int> path;
 7         DFS(nums,0,target,path,result);
 8         return result;    
 9         
10     }
11     void DFS(vector<int> &nums,int start,int gap,vector<int> path,vector<vector<int>> &result)
12     {   
13         //找到一个合法解
14         if(gap==0)
15         {
16             result.push_back(path);
17             return;
18         }
19         
20         for(int i=start;i<nums.size();i++)
21         {
22             //剪枝
23             if(gap<nums[i]) return;
24             
25             path.push_back(nums[i]);  //执行扩展动作
26             DFS(nums,i,gap-nums[i],path,result);
27             path.pop_back(); //撤销动作
28         }
29         
30     }
31 };

 

posted @ 2015-08-27 13:39  尾巴草  阅读(190)  评论(0编辑  收藏  举报