JAVA求集合中的组合
生活随笔
收集整理的這篇文章主要介紹了
JAVA求集合中的组合
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
好幾個月沒弄代碼了,今天弄個求組合的DEMO
思路是將集合的每個值對照一個索引,索引大小是集合的大小+2.索引默認(rèn)為[000...000],當(dāng)組合后選取的組合值demo為[0100..00]。然后根據(jù)遍歷索引來到集合中取值。
上代碼:
import java.util.ArrayList; import java.util.Iterator; import java.util.List;public class ComBit {public static void main(String[] args) {// Integer testint[] combination = new int[] { 1, 2, 3, 4 };List<Integer> combinationlist = new ArrayList<Integer>();for (Integer integer : combination) {combinationlist.add(integer);}ComBitIterator<Integer> i = new ComBitIterator<Integer>(combinationlist);while (i.hasNext()) {Object obj = i.next();System.out.println(obj.toString());}// String testString[] str = new String[] { "apple", "orange", "tomato", "potato" };List<String> combinationSlist = new ArrayList<String>();for (String s : str) {combinationSlist.add(s);}ComBitIterator<String> ii = new ComBitIterator<String>(combinationSlist);while (ii.hasNext()) {Object obj = ii.next();System.out.println(obj.toString());}}}class ComBitIterator<T> implements Iterator<T> {private int[] _bitArray = null;protected final int _length;protected final List<T> combination;protected List<T> _currentSet;public ComBitIterator(List<T> combination) {_currentSet = new ArrayList<T>();this._length = combination.size();this._bitArray = new int[_length + 2];this.combination = combination;}@Overridepublic boolean hasNext() {return _bitArray[_length + 1] != 1;}@SuppressWarnings("unchecked")@Overridepublic T next() {_currentSet.clear();for (int index = 1; index <= _length; index++) {if (_bitArray[index] == 1) {T value = combination.get(index - 1);_currentSet.add(value);}}int i = 1;while (_bitArray[i] == 1) {_bitArray[i] = 0;i++;}_bitArray[i] = 1;return (T) _currentSet;}}------------------------------------------------分割線---------------------------------------------------------
PS:代碼源于要求求數(shù)字1-20中 任取N的組合后合值為36,于是思路想到兩種,第一種是遞歸,第二種雖然也是遞歸,但是想弄個通用的,就有了以上的代碼。另外群里有人寫出了直接遞歸的代碼,也附上:
public static void main(String[] args) {combinateDataOfRange(1, 20, 36);}public static void combinateDataOfRange(int min, int max, int target) {combinateData(0, min, max, target, new Stack<Integer>());}public static void combinateData(int sum, int min, int max, int target,Stack<Integer> stack) {for (int i = stack.isEmpty() ? min : (Integer) stack.lastElement() + 1; i < max; ++i) {int tempSum = sum + i;stack.push(i);if (tempSum == target) {System.out.println(stack + "=" + target);} else {combinateData(tempSum, min, max, target, stack);}stack.pop();}}?
轉(zhuǎn)載于:https://www.cnblogs.com/GYoungBean/p/4567023.html
總結(jié)
以上是生活随笔為你收集整理的JAVA求集合中的组合的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Linux内核源码目录说明
- 下一篇: 斗鱼直播源解析工具