{
  "type": "code_options",
  "author": "https://github.com/qiyuangong/leetcode",
  "source": "solution.md",
  "exercise_id": "e3ee6d55eb8c45bc84201e59c85c5a01",
  "keywords": "数组,回溯",
  "title": "组合总和 II",
  "desc": [
    {
      "content": "\n<p>给定一个数组&nbsp;<code>candidates</code>&nbsp;和一个目标数&nbsp;<code>target</code>&nbsp;，找出&nbsp;<code>candidates</code>&nbsp;中所有可以使数字和为&nbsp;<code>target</code>&nbsp;的组合。\n</p>\n<p><code>candidates</code>&nbsp;中的每个数字在每个组合中只能使用一次。</p>\n<p><strong>说明：</strong></p>\n<ul>\n<li>所有数字（包括目标数）都是正整数。</li>\n<li>解集不能包含重复的组合。&nbsp;</li>\n</ul>\n<p><strong>示例&nbsp;1:</strong></p>\n<pre><strong>输入:</strong> candidates =&nbsp;[10,1,2,7,6,1,5], target =&nbsp;8,<strong><br />所求解集为:</strong>[[1, 7],[1, 2, 5],[2, 6],[1, 1, 6]]</pre>\n<p><strong>示例&nbsp;2:</strong></p>\n<pre><strong>输入:</strong> candidates =&nbsp;[2,5,2,1,2], target =&nbsp;5,<strong><br />所求解集为:</strong>[[1,2,2],[5]]</pre>",
      "language": "markdown"
    }
  ],
  "answer": [
    {
      "content": "",
      "language": "python"
    }
  ],
  "prepared": [
    [
      {
        "content": "",
        "language": "python"
      }
    ],
    [
      {
        "content": "",
        "language": "python"
      }
    ],
    [
      {
        "content": "",
        "language": "python"
      }
    ]
  ],
  "template": {
    "content": "class Solution(object):\n\tdef combinationSum2(self, candidates, target):\n\t\t\"\"\"\n\t\t:type candidates: List[int]\n\t\t:type target: int\n\t\t:rtype: List[List[int]]\n\t\t\"\"\"\n\t\tcandidates.sort()\n\t\tdp = [[] for _ in range(target + 1)]\n\t\tdp[0].append([])\n\t\tfor i in range(1, target + 1):\n\t\t\tfor j in range(len(candidates)):\n\t\t\t\tif candidates[j] > i:\n\t\t\t\t\tbreak\n\t\t\t\tfor k in range(len(dp[i - candidates[j]])):\n\t\t\t\t\ttemp = dp[i - candidates[j]][k][:]\n\t\t\t\t\tif len(temp) > 0 and temp[-1] >= j:\n\t\t\t\t\t\tcontinue\n\t\t\t\t\ttemp.append(j)\n\t\t\t\t\tdp[i].append(temp)\n\t\tres = []\n\t\tcheck = {}\n\t\tfor temp in dp[target]:\n\t\t\tvalue = [candidates[t] for t in temp]\n\t\t\ttry:\n\t\t\t\tcheck[str(value)] += 1\n\t\t\texcept KeyError:\n\t\t\t\tcheck[str(value)] = 1\n\t\t\t\tres.append(value)\n\t\treturn res\n# %%\ns = Solution()\nprint(s.combinationSum2(candidates = [2,5,2,1,2], target = 5))",
    "language": "python"
  },
  "node_id": "dailycode-237fc188faa44250a488a2ae809d34e8",
  "license": "csdn.net",
  "created_at": 1637894159,
  "topic_link": "https://bbs.csdn.net/topics/600470928"
}