zoukankan      html  css  js  c++  java
  • 39. Combination Sum java solutions

    Given a set of candidate numbers (C) 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]
    ]
    
     1 public class Solution {
     2     public List<List<Integer>> ans = new ArrayList<List<Integer>>();
     3     public List<List<Integer>> combinationSum(int[] candidates, int target) {
     4         List<Integer> list = new ArrayList<Integer>();
     5         combination(list,candidates,target,0,0);
     6         return ans;
     7     }
     8     
     9     public void combination(List<Integer> list, int[] can, int target, int sum, int s){
    10         if(sum == target){
    11             List<Integer> tmp = new ArrayList<Integer>(list);
    12             ans.add(tmp);
    13             return;
    14         }
    15         if(sum > target) return;
    16         for(int i = s; i < can.length; i++){
    17             list.add(can[i]);
    18             combination(list,can,target,sum+can[i],i);
    19             list.remove(list.size()-1);
    20         }
    21     }
    22 }

    都是套路。 N queen 问题掌握了就OK

  • 相关阅读:
    IntelliJ Idea使用代码折叠
    c# 文件属性读取操作及文件之间操作
    c#文件操作
    c++头文件 #include<iostream>
    基本SQL语句
    dd
    c#属性中的get和set属性
    c#
    c#运算表达式
    c#方法
  • 原文地址:https://www.cnblogs.com/guoguolan/p/5668139.html
Copyright © 2011-2022 走看看