1. 程式人生 > 實用技巧 >手撕_2

手撕_2

1、1,2...n,中隨意取幾個數,使其和等於sum,把所有可能組合列出來(和組合總和類似)

package mianjing;


import java.util.ArrayList;
import java.util.List;

public class test_2 {
//1,2...n,中隨意取幾個數,使其和等於target,把所有可能組合列出來
    public static void main(String[] args) {
        int n=10;
        int target = 20;
        if(target<n) {
            n
=target; } List<List<Integer>> result =combinationSum(n,target); System.out.println(result.toString()); } static List<List<Integer>> list1 = new ArrayList<>(); public static List<List<Integer>> combinationSum(int n, int
target) { List<Integer> list2 = new ArrayList<>(); dfc(1,n,list2,target); return list1; } public static void dfc(int begin,int len,List<Integer> list2,int target) { if(target == 0) { if(!list1.contains(new ArrayList<>(list2))) { list1.add(
new ArrayList<>(list2)); } return; } for(int i = begin; i < len; i++) { if(target-i < 0) { break; } list2.add(i); dfc(i+1,len,list2,target-i); list2.remove(list2.size()-1); } } }