• Combination sum


    Given a set of candidate numbers (C) (without duplicates) 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]
    ]
    

     从数组中找出和为target的组合,每个元素可以使用多次。。

    题目是枚举所有可能性的结果,所以可以使用回溯,尝试着看看是否满足要求。

    class Solution {
    public List<List<Integer>> combinationSum(int[] nums, int target) {
       /**
       这个题是穷举所有情况,回溯的可能性比较大
       */
            Arrays.sort(nums);
        List<List<Integer>> result=new ArrayList<List<Integer>>();
        backtracking(result,new ArrayList<Integer>(),nums,target,0,0);
        return result;
        }
        
        public void backtracking(List<List<Integer>> result,List<Integer> tmp,int[] nums,int target,int sum,int index){
            if(sum>target) return ;
            if(sum==target) {
                result.add(new ArrayList<Integer>(tmp));
                return ;
            }
            
            if(index>nums.length-1) return ;
            
            for(int i=index;i<nums.length;i++){
                tmp.add(nums[i]);
                backtracking(result,tmp,nums,target,sum+nums[i],i);
                tmp.remove(tmp.size()-1);
            }
        }
    }
  • 相关阅读:
    ASP.NET Core
    ASP.NET Core
    ASP.NET Core
    ASP.NET Core
    通用查询设计思想(2)- 基于ADO.Net的设计
    API接口通讯参数规范(2)
    Centos7 安装selenium(python3.7 centos7 )
    mysql (create temporary table table_name )临时表创建
    C# 字符串 String、StringBuffer和StringBuilder的区别
    安装Elasticsearch
  • 原文地址:https://www.cnblogs.com/xiaolovewei/p/8116954.html
Copyright © 2020-2023  润新知