题解 | #组合#

组合

http://www.nowcoder.com/practice/7cfd3675cc964ae6818a771ac97ece5f

import java.util.*;


public class Solution {
    
    ArrayList<ArrayList<Integer>> res = new ArrayList<>();
    
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param n int整型 
     * @param k int整型 
     * @return int整型ArrayList<ArrayList<>>
     */
    public ArrayList<ArrayList<Integer>> combine (int n, int k) {
        // write code here
        int[] nums = new int[n];
        for (int i = 0; i < n; i++) {
            nums[i] = i + 1;
        }
        ArrayList<Integer> currentArr = new ArrayList<>();
        process(currentArr, nums, 0, k);
        return res;
    }
    
    public void process(ArrayList<Integer> currentArr, int[] nums, int index, int k) {
        if (currentArr.size() == k) {
            ArrayList<Integer> copyArr = new ArrayList<>();
            copyArr.addAll(currentArr);
            res.add(copyArr);
            return;
        }
        if (index >= nums.length) {
            return;
        }
        process(currentArr, nums, index + 1, k);
        ArrayList<Integer> tmpArr = new ArrayList<>();
        tmpArr.addAll(currentArr);
        tmpArr.add(nums[index]);
        process(tmpArr, nums, index + 1, k);
    }
}
全部评论

相关推荐

点赞 评论 收藏
分享
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务