Java找出数字组合的方法是什么

63次阅读
没有评论

共计 2218 个字符,预计需要花费 6 分钟才能阅读完成。

这篇文章主要介绍“Java 找出数字组合的方法是什么”,在日常操作中,相信很多人在 Java 找出数字组合的方法是什么问题上存在疑惑,丸趣 TV 小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”Java 找出数字组合的方法是什么”的疑惑有所帮助!接下来,请跟着丸趣 TV 小编一起来学习吧!

给出一组候选数字 (C) 和目标数字(T), 找到 C 中所有的组合,使找出的数字和为 T。C 中的数字可以无限制重复被选取。例如, 给出候选数组 [2,3,6,7] 和目标数字 7
所求的解为:[7]  和  [2,2,3]
给定一个数组,从中找出一组数来,使其和等于 target。数组无序,但都是正整数。与 40 题比较
I 和 II 不同的是,I 数组里没有重复的数,但一个数可以用多次;II 数组里有重复,一个数只能用一次。I 和 II 都要求返回结果中没有重复的解,且每个解中的数都按非递减排好序。
package com.lifeibigdata.algorithms.leetcode;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
 * Created by lifei on 16/7/4.
 */
public class CombinationSum { public static void main(String[] args) { int[] can = new int[]{5,3,2,1};
 CombinationSum cs = new CombinationSum();
 cs.combinationSum(can,6);
 for (List Integer  list:ans) { for (int i:list) {
 System.out.print(i+ , 
 }
 System.out.println();
 }
 }
// static List List Integer  result;
// List Integer  solu;
// public List List Integer  combinationSum(int[] candidates, int target) {// result = new ArrayList ();
// solu = new ArrayList ();
// Arrays.sort(candidates);
// getCombination(candidates, target, 0, 0);
// return result;
// }
// public void getCombination(int[] candidates, int target, int sum, int level){// if(sum target) return;
// if(sum==target){// result.add(new ArrayList (solu));
// return;
// }
// for(int i=level;i candidates.length;i++){// sum+=candidates[i];
// solu.add(candidates[i]);
// getCombination(candidates, target, sum, i);
// solu.remove(solu.size()-1);
// sum-=candidates[i];
// }
// }

 static List List Integer  ans = new ArrayList List Integer ();// 声明全局变量  int[] cans = {};  public List List Integer  combinationSum(int[] candidates, int target) {  this.cans = candidates;  Arrays.sort(cans);  backTracking(new ArrayList(), 0, target);  return ans;  }  public void backTracking(List Integer  cur, int from, int target) {// 初次 cur 为空  if (target == 0) { List Integer  list = new ArrayList Integer (cur);  ans.add(list);  } else { for (int i = from; i   cans.length   cans[i]  = target; i++) {// 界限条件  cur.add(cans[i]);  backTracking(cur, i, target - cans[i]); // 递归调用  cur.remove(new Integer(cans[i]));  }  }  }  /**  *  *  *  *  1,1,1,1,1,1,  1,1,1,1,2,  1,1,1,3,  1,1,2,2,  1,2,3,  1,5,    2,2,2,    3,3,  */ }

到此,关于“Java 找出数字组合的方法是什么”的学习就结束了,希望能够解决大家的疑惑。理论与实践的搭配能更好的帮助大家学习,快去试试吧!若想继续学习更多相关知识,请继续关注丸趣 TV 网站,丸趣 TV 小编会继续努力为大家带来更多实用的文章!

正文完
 
丸趣
版权声明:本站原创文章,由 丸趣 2023-08-16发表,共计2218字。
转载说明:除特殊说明外本站除技术相关以外文章皆由网络搜集发布,转载请注明出处。
评论(没有评论)