zoukankan      html  css  js  c++  java
  • leetcode 40. Combination Sum II

    题目内容

    Given a collection of candidate numbers (candidates) and a target number (target), find all unique combinations in candidates where the candidate numbers sums to target.
    
    Each number in candidates may only be used once in the combination.
    
    Note:
    
    All numbers (including target) will be positive integers.
    The solution set must not contain duplicate combinations.
    
    Example:
    Input: candidates = [10,1,2,7,6,1,5], target = 8,
    A solution set is:
    [
      [1, 7],
      [1, 2, 5],
      [2, 6],
      [1, 1, 6]
    ]
    Example 2:
    
    Input: candidates = [2,5,2,1,2], target = 5,
    A solution set is:
    [
      [1,2,2],
      [5]
    ]
    
    

    分析过程

    • 题目归类:
      使用后删除类题目
    • 题目分析:
      递归处理使用后删除即可。掌握方法就很简单
    • 边界分析:
      • 空值分析
      • 循环边界分析
    • 方法分析:
      • 数据结构分析
      • 状态机
      • 状态转移方程
      • 最优解
    • 测试用例构建

    代码实现

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

    效率提高

    拓展问题

  • 相关阅读:
    beta冲刺——用户使用调查报告
    专业团队——Beta计划总结随笔
    专业团队测试随笔
    Beta冲刺--第十次随笔
    Beta冲刺--第九次随笔(md文档问题的解决)
    Beta冲刺--第八次随笔
    Beta冲刺--第七次随笔(仓库优化)
    Beta冲刺--第六次随笔(仓库修改)
    Beta冲刺--第五次随笔
    Beta冲刺--第四次随笔
  • 原文地址:https://www.cnblogs.com/clnsx/p/12335252.html
Copyright © 2011-2022 走看看