The basic idea, shown in the previous blog
http://blog.csdn.net/u010204902/article/details/8803342
is to use DFS
I tried to use non-recursive method to do the DFS. I need to maintain a stack by myself. It does not appear to be faster than using recursion.
It pass the large test around 80 ms
class Solution {
public:
vector<vector<int> > combinationSum(vector<int> &candidates, int target) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
unique(candidates.begin(), candidates.end());
sort(candidates.begin(), candidates.end());
vector<vector<int>> ret;
int max_size = target/candidates.front();
vector<int> put_num(max_size+1);
vector<int> idx(max_size+2);
for(size_t i=0; i<max_size; i++)
idx[i] = -1;
idx[0] = 0;
size_t length = 1;
put_num[0] = candidates[0];
target -= candidates[0];
while(length){
if(target <= 0) {
if(target == 0)
ret.push_back(vector<int>(put_num.begin(), put_num.begin()+length));
target += put_num[length - 1];
length --;
} else {
if(idx[length] == -1){
idx[length] = idx[length-1];
put_num[length] = candidates[idx[length-1]];
target -= put_num[length];
idx[length+1] = -1;
length++;
} else {
target += put_num[length - 1];
if(idx[length-1]<candidates.size()-1){
idx[length-1]++;
put_num[length-1] = candidates[idx[length-1]];
target -= put_num[length-1];
idx[length] = -1;
} else
length --;
}
}
}
return ret;
}
};