zoukankan      html  css  js  c++  java
  • [leetcode]Combination Sum II

    有了前几题的经验,这道题也很快过了。

    有序添加,每一次DFS都是找解中的第i个元素。

    public class Solution {
        ArrayList<ArrayList<Integer>> ans = new ArrayList<ArrayList<Integer>>();
        ArrayList<Integer> tmp = new ArrayList<Integer>();
        public ArrayList<ArrayList<Integer>> combinationSum2(int[] candidates, int target) {
            ans.clear();
            tmp.clear();
            Arrays.sort(candidates);
            boolean used[] = new boolean[candidates.length];
            sub(candidates, 0, 0, target, used);
            return ans;
        }
         
        private void sub(int[] candidates, int pos, int sum, int target, boolean used[])
        {
            if (sum > target) return;
            else if (sum == target)
            {
                ArrayList<Integer> arr = new ArrayList<Integer>(tmp);
                Collections.sort(arr);
                ans.add(arr);
            }
            else
            {
                for (int i = pos; i < candidates.length; i++)
                {
                    if (i!=0 && candidates[i] == candidates[i-1] && !used[i-1]) continue;
                    tmp.add(candidates[i]);
                    used[i] = true;
                    sub(candidates, i+1, candidates[i]+sum, target, used);
                    tmp.remove(tmp.size()-1);
                    used[i] = false;
                }
            }
        }
    }
    

      

  • 相关阅读:
    Excel Sheet Column Number
    Compare Version Numbers
    Min Stack
    Excel Sheet Column Title
    Find Peak Element
    数据规范化
    Majority Element
    用户唯一登录
    面试总结——Java高级工程师(三)
    Spring AOP 实战运用
  • 原文地址:https://www.cnblogs.com/lautsie/p/3332340.html
Copyright © 2011-2022 走看看