标签:
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:
For example, given candidate set 2,3,6,7
and
target 7
,
A solution set is:
[7]
[2, 2, 3]
vector<vector<int>> combinationSum(vector<int>& candidates, int target) { vector<vector<int>> res; if(candidates.size()==0) return res; if(target<=0) return res; int len=candidates.size(); sort(candidates.begin(),candidates.end()); stack<vector<int>> st; for(int i=candidates.size()-1;i>=0;i--) { vector<int>temp; temp.push_back(candidates[i]); if(accumulate(temp.begin() , temp.end() , 0)==target) res.push_back(temp); else if(accumulate(temp.begin() , temp.end() , 0)<target) st.push(temp); else ; } while(!st.empty())//用迭代的方法深度遍历,用栈实现,栈内元素为路径各节点值。 { vector<int> node=st.top(); st.pop(); int pre=accumulate(node.begin() , node.end() , 0); for(int i=candidates.size()-1;i>=0;i--) { vector<int> temp=node; temp.push_back(candidates[i]); if(accumulate(temp.begin() , temp.end() , 0)==target) { sort(temp.begin(),temp.end()); int flag=0; for(int j=0;j<res.size();j++)//判断res中是否已经加入该路径 { if(res[j].size()==temp.size()) { int t; for(t=0;t<temp.size();t++) { if(res[j][t]!=temp[t]) { break; } } if(t==temp.size()) { flag=1;//已有相同的并加入到了res } } } if(flag==0) res.push_back(temp); } else if(accumulate(temp.begin() , temp.end() , 0)<target) st.push(temp); else ; } } return res; }方法一优点:简单直观,缺点:代码略长,并且在leetcode中会判断超时,但是在VS下运行超时的用例可以得到结果且正确。
<pre name="code" class="cpp">class Solution { public: vector<vector<int>> res; vector<int> pre; void cm(vector<int>& p, int tag,int l) { if(l==pre.size()) return; int temp=accumulate(p.begin() , p.end() , 0); if(temp==tag) { res.push_back(p); return ; } else if(temp>tag) return; else { for(int i=l;i!=pre.size();i++)//因为candidates的元素可以重复使用,所以i=l { p.push_back(pre[i]); cm(p,tag,i); p.pop_back(); } } } vector<vector<int>> combinationSum(vector<int>& candidates, int target) { if(candidates.size()==0) return res; if(target<=0) return res; int len=candidates.size(); sort(candidates.begin(),candidates.end()); pre=candidates; vector<int> tmp;//tmp为所要求的子集 cm(tmp,target,0); return res; } };
版权声明:本文为博主原创文章,未经博主允许不得转载。
标签:
原文地址:http://blog.csdn.net/sinat_24520925/article/details/47058935