程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C++ >> 關於C++ >> leetcode筆記:Combination Sum II

leetcode筆記:Combination Sum II

編輯:關於C++

一. 題目描述

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 once number of times.

Note:
• 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 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]

二. 題目分析

該題與之前的Combination Sum的解法類似,均可使用深度優先搜索來解。不同的是該題需要注意如何避免組合重復,因為不能重復,所以要跳過一樣的數字。

例如:一個整數集合:[2 2 3],當我們要使用第二個2時,我們要檢查他的前面一個2是否使用了,當未被使用時第二個2就不能使用;。

三. 示例代碼

#include 
#include 
#include 

using namespace std;

class Solution
{
public:
    vector > combinationSum2(vector &candidates, int target)
    {
        vector temp; // 用於存放臨時組合
        sort(candidates.begin(), candidates.end());
        combinationDFS(candidates, temp, 0, target);
        return result;
    }

private:
    vector > result;

    void combinationDFS(vector &candidates, vector &temp, size_t index, int target)
    {
        if (target == 0)
        {
            result.push_back(temp);
            return;
        }

        else
        {
            int prev = -1;
            for (size_t i = index; i < candidates.size(); ++i)
            {
                // 由於candidates中元素可能有重復,以下操作的意義是判斷上輪循
                // 環是否選擇了candidates[i],是則跳過選擇下一個candidates元素
                // 直到下標到達比prev大的元素,選擇該元素進行下一輪遞歸
                if (prev == candidates[i])
                    continue;

                if (candidates[i] > target)
                    return;

                prev = candidates[i];
                temp.push_back(candidates[i]);
                combinationDFS(candidates, temp, i + 1, target - candidates[i]);
                temp.pop_back();
            }
        }
    }
};

這裡寫圖片描述

四. 小結

 

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved