39. Combination Sum I && II

来源:互联网 发布:软件使用说明怎么写 编辑:程序博客网 时间:2024/06/03 12:35
public class Solution {    public List<List<Integer>> combinationSum(int[] c, int t) {        if(c == null || c.length == 0){            return null;        }        List<List<Integer>> result = new ArrayList<List<Integer>>();        List<Integer> list = new ArrayList<Integer>();        dfs(c, t, result, list, 0);        return result;    }        public void dfs(int[] c, int t, List<List<Integer>> result, List<Integer> list, int index){        if(t == 0){            result.add(new ArrayList<Integer>(list));            return;        }        for(int i=index; i<c.length; i++){            if(t - c[i] >= 0){                list.add(c[i]);                dfs(c, t-c[i], result, list, i);                list.remove(list.size()-1);            }        }    }}

传index是因为之前传过的就不用传了。

Each number in C may only be used once in the combination.

public class Solution {        public List<List<Integer>> combinationSum2(int[] c, int t) {        if(c == null || c.length == 0){            return null;        }        Arrays.sort(c);        List<List<Integer>> result = new ArrayList<List<Integer>>();        List<Integer> list = new ArrayList<Integer>();        dfs(c, t, result, list, 0);        return result;    }        public void dfs(int[] c, int t, List<List<Integer>> result, List<Integer> list, int index){        if(t == 0){            result.add(new ArrayList<Integer>(list));            return;        }        for(int i=index; i<c.length; i++){            if(i != index && c[i] == c[i-1]){ // 每次循环的时候,取没有取过的元素                continue;            }            if(t - c[i] >= 0){                list.add(c[i]);                dfs(c, t-c[i], result, list, i+1);                list.remove(list.size()-1);            }        }    }}