leetcode 39. Combination Sum

题目内容

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;
    }
}

效率提高

拓展问题

posted @ 2020-02-20 12:40  clnsx  阅读(106)  评论(0编辑  收藏  举报