2017-01-08 56 views
-2

给定一组候选数(C)和目标数(T)的,找到在C中的所有唯一组合,其中所述候选号码款项T.组合萨姆

相同重复数目可以选自C无限选择次数。

All numbers (including target) will be positive integers. 
Elements in a combination (a1, a2, … , ak) must be in non-descending order. (ie, a1 ≤ a2 ≤ … ≤ ak). 
The combinations themselves must be sorted in ascending order. 
CombinationA > CombinationB iff (a1 > b1) OR (a1 = b1 AND a2 > b2) OR … (a1 = b1 AND a2 = b2 AND … ai = bi AND ai+1 > bi+1) 
The solution set must not contain duplicate combinations. 

实施例, 鉴于候选集2,3,6,7和目标7, 的溶液组是:

[2, 2, 3] [7]

溶液代码是:

class Solution { 
    public: 

    void doWork(vector<int> &candidates, int index, vector<int> &current, int currentSum, int target, vector<vector<int> > &ans) { 
     if (currentSum > target) { 
      return; 
     } 
     if (currentSum == target) { 
      ans.push_back(current); 
      return; 
     } 
     for (int i = index; i < candidates.size(); i++) { 
      current.push_back(candidates[i]); 
      currentSum += candidates[i]; 

      doWork(candidates, i, current, currentSum, target, ans); 

      current.pop_back(); 
      currentSum -= candidates[i]; 
     } 

    } 

    vector<vector<int>> combinationSum(vector<int> &candidates, int target) { 
     vector<int> current; 
     vector<vector<int> > ans; 
     sort(candidates.begin(), candidates.end()); 
     vector<int> uniqueCandidates; 
     for (int i = 0; i < candidates.size(); i++) { 
      if (i == 0 || candidates[i] != candidates[i-1]) { 
       uniqueCandidates.push_back(candidates[i]); 
      } 
     } 
     doWork(uniqueCandidates, 0, current, 0, target, ans); 
     return ans; 
    } 
}; 

现在,虽然我可以通过举例来了解解决方案,但是我怎么能够提出这样的解决方案。主要工作在这个功能:

for (int i = index; i < candidates.size(); i++) { 
     current.push_back(candidates[i]); 
     currentSum += candidates[i]; 

     doWork(candidates, i, current, currentSum, target, ans); 

     current.pop_back(); 
     currentSum -= candidates[i]; 
    } 

请告诉我如何理解上述代码以及如何去思考这个解决方案。我可以解决基本的递归问题,但这些看起来遥不可及。谢谢你的时间。

+0

为什么我会得到downvotes? – Gyanshu

+0

你很可能会收到降薪,因为人们觉得你要求别人为你做你的工作,而不是向你已经试图解决的问题寻求帮助。 –

+0

@MikelF我给了这个问题至少6小时。我不知道“尝试”的定义是什么? – Gyanshu

回答

1

那么代码通常做的就是:

  1. 排序给定的递增的顺序号。
  2. 删除集合中的重复项。
  3. 对于组中的每个数字:
    • 不断增加相同数量,直到总和或者大于或等于所述目标。
    • 如果相等,则保存组合。
    • 如果它更大,请删除最后添加的数字(返回上一步骤),并开始将该集合中的下一个数字添加到总和中。

对于理解递归,我想先从最简单的情况。让我们来看看,例如: Candidates: { 2, 2, 1 } Target: 4

排序和删除重复项变更设定为{1,2}。递归顺序将为:

  • Sum = 1;
    • Sum = 1 + 1;
      • Sum = 1 + 1 + 1;
        • Sum = 1 + 1 + 1 + 1; (与目标相同,保存组合)
        • Sum = 1 + 1 + 1 + 2; (大于目标,不再增加数字)
      • Sum = 1 + 1 + 2; (保存组合,不再需要添加数字)
    • Sum = 1 + 2;
      • Sum = 1 + 2 + 2; (较大的,没有更多的数)
  • 萨姆= 2;
    • Sum = 2 + 2; (保存,这是最后一次递归)
+0

谢谢,但你可以告诉我如何拿出递归函数。我的意思是我的思考过程应该是一步一步明智的,抱歉太天真了。 – Gyanshu

+0

非常感谢。我现在明白了。 – Gyanshu