leetCode练习(39)

来源:互联网 发布:你看的我是蓝色的 知乎 编辑:程序博客网 时间:2024/06/05 00:23

题目:Combination Sum

难度:medium

问题描述:

Given a set of candidate numbers (C) and a target number (T), find all unique combinations inC where the candidate numbers sums to T.

The same repeated number may be chosen from C unlimited number of times.

Note:

  • All numbers (including target) will be positive integers.
  • The solution set must not contain duplicate combinations.

For example, given candidate set [2, 3, 6, 7] and target 7,
A solution set is:

[  [7],  [2, 2, 3]]

解题思路:前面出现过固定的4数和、3数和等于定值的题目,现在出现了更一般的题目,即不定长和等于定值。当然了,对于前面题目熟悉的同学一定很容易想到使用backtracking方法。使用回溯法,在此题中要注意两点,一是给定的数组要是【2,2,3】这种带重复的情况,我们通过if(nums[I]==nums[I-1])来判断此时调用的‘2’前面是否已经调用过(包含前面一个2的所有可能一定包含了含有后面一个2的所有可能)。二是本题,一个nums[I]可以重复多次,因此迭代时的起始位置不是下一个数,而是i本身。

具体代码如下:

0 0
原创粉丝点击