摘要:題目為求從到的自然數(shù)里取個(gè)數(shù)的所有組合全集。使用遞歸的模板,建立函數(shù)。模板如下也可以不建立新的,而是遞歸調(diào)用之后刪去中最后一個(gè)元素
Problem
Given two integers n and k, return all possible combinations of k numbers out of 1 ... n.
ExampleFor example,
If n = 4 and k = 2, a solution is:
[[2,4],[3,4],[2,3],[1,2],[1,3],[1,4]]
題目為求從1到n的自然數(shù)里取k個(gè)數(shù)的所有組合全集。使用遞歸的模板,建立helper函數(shù)。
模板如下:
void helper(range S, target T, start A, tempArray B) { if (B met T or other requirement) { res.add(B); return; } for (int i starts from A in S) { tempArray C = new tempArray (B); C.add(i); helper(S, T-i, i+1, C); } }
也可以不建立新的tempArray C,而是遞歸調(diào)用helper之后刪去B中最后一個(gè)元素:
void helper(range S, target T, start A, tempArray B) { if (B met T or other requirement) { res.add(B); return; } for (int i starts from A in S) { B.add(i); helper(S, T-i, i+1, C); B.remove(B.size()-1); } }Solution
public class Solution { List> res = new ArrayList
>(); public List
> combine(int n, int k) { helper(n, k, 1, new ArrayList
()); return res; } private void helper(int n, int k, int start, List pre) { if (pre.size() == k) { res.add(pre); return; } for (int i = start; i <= n; i++) { List cur = new ArrayList (pre); cur.add(i); helper(n, k, i+1, cur); } } }
文章版權(quán)歸作者所有,未經(jīng)允許請勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。
轉(zhuǎn)載請注明本文地址:http://www.ezyhdfw.cn/yun/65722.html