码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode 39. Combination Sum

时间:2020-02-20 13:09:06      阅读:53      评论:0      收藏:0      [点我收藏+]

标签:and   状态   including   arraylist   get   rom   where   方法   删除   

题目内容

Given a set of candidate numbers (candidates) (without duplicates) and a target number (target), find all unique combinations in candidates where the candidate numbers sums to target.

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

Note:

All numbers (including target) will be positive integers.
The solution set must not contain duplicate combinations.
Example:
Input: candidates = [2,3,6,7], target = 7,
A solution set is:
[
  [7],
  [2,2,3]
]
Example 2:

Input: candidates = [2,3,5], target = 8,
A solution set is:
[
  [2,2,2,2],
  [2,3,3],
  [3,5]
]

分析过程

  • 题目归类:
    删除类型,在处理后需要删除值的问题。
  • 题目分析:

  • 边界分析:
    • 空值分析
    • 循环边界分析
  • 方法分析:
    • 数据结构分析
    • 状态机
    • 状态转移方程
    • 最优解
  • 测试用例构建

代码实现


import java.util.*;
class Solution {
    List<List<Integer>> list = new ArrayList<>();
    List<Integer> arraylist = new ArrayList<>();
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        Arrays.sort(candidates);
        return Sum(candidates,target,0);
    }
    List<List<Integer>> Sum(int[] candidates, int target,int s) {
        
        if(target <0)
            return list;
        if(target == 0){
            ArrayList<Integer> k = new ArrayList<>(arraylist);
            Collections.sort(k);
            if(!list.contains(k)){
                list.add(new ArrayList<Integer>(k));
            }
            return list;
        }
        
        if(candidates[0]>target){
            return list;
        }
        
        for(int i = s; i < candidates.length; i++) {
            arraylist.add(candidates[i]);
            Sum(candidates,target-candidates[i],i);
            arraylist.remove(arraylist.size()-1);
        }
        
        return list;
    }
}

效率提高

拓展问题

leetcode 39. Combination Sum

标签:and   状态   including   arraylist   get   rom   where   方法   删除   

原文地址:https://www.cnblogs.com/clnsx/p/12335212.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!