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;
                }
            }
        }
    }
    

      

  • 相关阅读:
    Go--指针
    Go--struct
    Go--函数
    Go基础
    流程控制
    Go前言
    变量与常量
    Django(三):HttpRequest和HttpResponse
    Django(二):url和views
    tensorflow(一):图片处理
  • 原文地址:https://www.cnblogs.com/lautsie/p/3332340.html
Copyright © 2011-2022 走看看