【leetcode】Combination Sum II

Combination Sum II

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] 

 
要考虑去重
 
每次都从当前位置选取元素,遇到重复的直接跳过就可以了
 
 
 1 class Solution {

 2 

 3 public:

 4 

 5    

 6 

 7     vector<vector<int> > combinationSum2(vector<int> &candidates, int target)

 8 

 9     {

10 

11        

12 

13         sort(candidates.begin(),candidates.end());

14 

15         vector<vector<int> > result;

16 

17         vector<int> tmp;

18 

19  

20 

21         backtracking(result,candidates,target,tmp,0,0);

22 

23        

24 

25         return result;

26 

27     }

28 

29    

30 

31     void backtracking(vector<vector<int> > &result,vector<int> &candidates, int &target,vector<int> tmp, int sum,int index)

32 

33     {

34 

35  

36 

37         if(sum==target)

38 

39         {

40 

41             result.push_back(tmp);

42 

43             return;

44 

45         }

46 

47         else

48 

49         {

50 

51             int sum0=sum;

52 

53            

54 

55             for(int i=index;i<candidates.size();i++)

56 

57             {

58 

59                 if(i>index&&candidates[i]==candidates[i-1])

60 

61                 {

62 

63                     continue;

64 

65                 }

66 

67                

68 

69                 tmp.push_back(candidates[i]);

70 

71                

72 

73                

74 

75                 sum=sum0+candidates[i];

76 

77                 if(sum>target)

78 

79                 {

80 

81                     break;

82 

83                 }            

84                 backtracking(result,candidates,target,tmp,sum,i+1);

85 

86                 tmp.pop_back();

87 

88             }            

89 

90         }        

91 

92     }

 

    
 

你可能感兴趣的:(LeetCode)