leetcode 39. Combination Sum

来源:互联网 发布:js判断手机横屏竖屏 编辑:程序博客网 时间:2024/06/16 23:13

Given a set of candidate numbers (C(without duplicates) 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 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]]

Subscribe to see which companies asked this question.

给定一个无重复数字的数组和一个目标值,返回所有数组中相加能得到目标值的组合,每个数字可以使用多次。

这种返回所有可能性的题,一般都是递归吧。。那我们就强行递归吧,由于考虑到重复利用,所以每一个值一直使用到等于或大于目标值再试下一个值。

import java.util.ArrayList;public class Solution {    public List<List<Integer>> combinationSum(int[] candidates, int target) {        List<List<Integer>>ans = new ArrayList<List<Integer>>();        List<Integer>list = new ArrayList<Integer>();        if(candidates.length==0){            return ans;        }        Arrays.sort(candidates);        helper(candidates,target,0,list,ans);        return ans;    }    public void helper(int[]candidates,int target,int beg,List<Integer>list,List<List<Integer>>ans){        if(target<0)return ;        if(target==0){            ans.add(new ArrayList<Integer>(list));            return ;        }        for(int i=beg;i<candidates.length;i++){            list.add(candidates[i]);            helper(candidates,target-candidates[i],i,list,ans);            list.remove(list.size()-1);        }    }}


原创粉丝点击