共計 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 小編會繼續努力為大家帶來更多實用的文章!
正文完