Combination Sum:非重复数组中选取若干元素求和等于给定值

来源:互联网 发布:豫章学院 知乎 编辑:程序博客网 时间:2024/06/05 14:36


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]]

注意:给顶元素不重复,但是一个元素可以被多次选取

思路:深度优先遍历,注意同意元素可被取多次,所以递归调用时仍从当前元素下表调用,打印数组时要注意每个元素被选取次数。

class Solution {      public List<List<Integer>> combinationSum(int[] candidates, int target) {          List<List<Integer>> list = new ArrayList<>();         Arrays.sort(candidates);          dfs(candidates,0,0,target,list);              return list;                }      static int[] index = new int[10000];       public static void dfs(int[] candidates,int sum,int i,int target,List list){          if(sum>target) return;          if(sum==target){              ArrayList<Integer> l = new ArrayList();              for(int j=0;j<candidates.length;j++){                  if(index[j]!=0){                         for(int c = index[j];c>0;c--){                        l.add(candidates[j]);                     }                               }              }              list.add(l);              return;          }else{              for(int j = i ;j<candidates.length;j++){                  index[j]++;                  dfs(candidates,sum+candidates[j],j,target,list);                  index[j]--;              }          }      }  }  


阅读全文
0 0
原创粉丝点击