zoukankan      html  css  js  c++  java
  • 组合数

    问题: 给n个不同的正整数, 取m个数使得和为sum, 其中任意数可以重复取多次

    例如:set [2, 3, 6, 7] and target 7, 结果有[7] ,[2,2,3] 

    public class Solution {
        public List<List<Integer>> combinationSum(int[] candidate, int sum){       
            List<List<Integer>> res = new ArrayList<List<Integer>>();
            //corner

            //core
            List<Integer> path = new ArrayList<>();

            Arrays.sort(candidate);

            helper(res, path, candidate, sum, 0);        //start from position = 0

            return res;
        }

        public void helper(List<List<Integer>> res, List<Integer> path, int[] candidate, int sum, int position){
            //base
            if ( sum == 0 ){                                   
                res.add(new ArrayList<Integer>(path));
                return ;                                       
            }

            //current
            for ( int i = position; i < candidate.length && sum >= candidate[i]; i++ ){   
                path.add(candidate[i]);
                //next: pass down remaining 'sum', and afterwards 'start position'
                helper(res, path, candidate, sum - candidate[i], i);       
                path.remove(path.size() - 1);
            }

            return ;
        }
    }

  • 相关阅读:
    GSS3 SPOJ 1716. Can you answer these queries III gss1的变形
    GSS1 spoj 1043 Can you answer these queries I 最大子段和
    Codeforces Round #197 (Div. 2) C,D两题
    sgu 185 最短路建网络流
    CF 208E
    QTREE2 spoj 913. Query on a tree II 经典的倍增思想
    BZOJ 1146: [CTSC2008]网络管理Network 树链剖分+线段树+平衡树
    ubuntu安装vim
    历史背景更新模型
    码本模型
  • 原文地址:https://www.cnblogs.com/energy1010/p/6867391.html
Copyright © 2011-2022 走看看