LeetCode_OJ【39】Combination Sum

来源:互联网 发布:苹果版软件商店 编辑:程序博客网 时间:2024/06/03 12:36

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.
  • Elements in a combination (a1, a2, … ,ak) must be in non-descending order. (ie, a1a2 ≤ … ≤ ak).
  • 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]


给定数组和目标值,从数组中找到所有的组合,使得组合的总和等于目标值,数组中的值可以重复选取。

这个题目的主要思路就是递归回溯,说来惭愧,好久没写递归,答案还是参考了别人的。

下面是本题的java实现。

public class Solution {public List<List<Integer>> combinationSum(int[] candidates, int target) {List<List<Integer>> res = new ArrayList<List<Integer>>();List<Integer> tmp = new ArrayList<Integer>();dfs(res,tmp,candidates,target,0);return res;    }public void dfs(List<List<Integer>> res,List<Integer> tmp,int[] candidates, int gap,int index){if(gap == 0){List<Integer> list = new ArrayList<Integer>(tmp); res.add(list);return;}for(int i = index ; i < candidates.length; i++){if(gap < candidates[index])return;else{tmp.add(candidates[i]);gap -= candidates[i];dfs(res,tmp,candidates,gap,i);tmp.remove(tmp.size()-1);}}}}


0 0