zoukankan      html  css  js  c++  java
  • 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 1:

    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]
    ]

     1 class Solution {
     2     
     3     public void dfs(List<List<Integer>> ans, int []candidates, int pos, int target, ArrayList<Integer> temp) {
     4         if (target == 0) {
     5             
     6             
     7             ans.add(new ArrayList<>(temp));
     8            
     9             return;
    10         }
    11         if (target < candidates[pos]) {
    12             return;
    13         }
    14         int n = candidates.length;
    15         System.out.println(pos);
    16         for (int i = pos; i < n && candidates[i] <= target; ++i) {
    17             temp.add(candidates[i]);
    18             dfs(ans, candidates, i, target - candidates[i],  temp);
    19             temp.remove(temp.size() - 1);
    20         }
    21     }
    22     public List<List<Integer>> combinationSum(int[] candidates, int target) {
    23         Arrays.sort(candidates);
    24         List<List<Integer>> ans = new ArrayList<>();
    25         if (candidates.length == 0) return ans;
    26         int n = candidates.length;
    27         ArrayList<Integer> temp = new ArrayList<>();
    28         dfs(ans, candidates, 0, target, temp);
    29         return ans;
    30     }
    31 }
  • 相关阅读:
    滚动相册
    智能拼图
    连连看
    魔法色块
    ASP.NET Session的七点认识
    从11月开始windows update速度缓慢,中国反击?
    WM实现文件关联
    与黄河老师合影
    ubuntu8.04笔记本开启无线网卡记得开网卡的电源
    无法在Web服务器上启动调试,与Web服务器通信时出现身份验证错误
  • 原文地址:https://www.cnblogs.com/hyxsolitude/p/12315463.html
Copyright © 2011-2022 走看看