Monday, June 24, 2013

combination sum II@leetcode

刷题必备书籍Cracking the Coding Interview: 150 Programming Questions and Solutions 

简历:The Google Resume: How to Prepare for a Career and Land a Job at Apple, Microsoft, Google, or any Top Tech Company
算法学习书籍:Introduction to Algorithms
编程珠玑:Programming Pearls (2nd Edition)
C++ 学习:The C++ Programming Language, 4th Edition
经典操作系统书籍,龙书:Operating System Concepts
创业:The Start-up of You: Adapt to the Future, Invest in Yourself, and Transform Your Career
Given a collection of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T.
Each number in C may only be used once in the combination.
Note:
  • All numbers (including target) will be positive integers.
  • Elements in a combination (a1a2, � , ak) must be in non-descending order. (ie, a1 ? a2 ? � ? ak).
  • The solution set must not contain duplicate combinations.
For example, given candidate set 10,1,2,7,6,1,5 and target 8
A solution set is: 
[1, 7] 
[1, 2, 5] 
[2, 6] 
[1, 1, 6] 
» Solve this problem

思路没太多差别,关键还是去重复,用的方法也和PERMUTATIONS II一样。
class Solution {
public:
void combineSum(vector<int> &candidates, int &sum, int begin, int target, vector<int> &visited, vector<int> &solution, vector<vector<int> > &res)
{
if(sum==target)
{
res.push_back(solution);
return;
}
if(sum>target)
return;
for(int i=begin; i<candidates.size(); i++)
{
if(candidates[i]<=target&&visited[i]==0)
{
if(i>0 && candidates[i]==candidates[i-1] && visited[i-1]==0)
continue;
visited[i]=1;
solution.push_back(candidates[i]);
sum+=candidates[i];
combineSum(candidates, sum, i, target, visited, solution, res);
sum-=candidates[i];
solution.pop_back();
visited[i]=0;
}
}
}
vector<vector<int> > combinationSum2(vector<int> &num, int target) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
vector<int> solution;
vector<vector<int> > res;
vector<int> visited(num.size(), 0);
if(num.empty()) return res;
sort(num.begin(), num.end());
int sum=0;
combineSum(num, sum, 0, target, visited, solution, res);
return res;
}
};

1 comment:

  1. 谢谢你的blog。一个小的改进,既然sort了原来的list,就没有必要用一个vector来记visited,可以只用一个variable,叫nextIndex,然后每次for循环选candidate就从A[nextIndex:end]里面选。

    ReplyDelete

Leetcode 316. Remove Duplicate Letters

 这道题表面问的是如何删除重复,实际在问如何从多个字符选取一个保留,从而让整个字符串按升序排列。那么策略就是对于高顺位的字符比如‘a',就要选靠前位置的保留,而低顺位字符如’z'则应该尽量选取靠后位置保留。 算法大概思路:每看到一个字符,我们要决定是否保留 1. ...