Leetcode - Subsets

1190 단어
기본 문제, 거슬러 올라가기 코드:
public class Solution {
    public ArrayList<ArrayList<Integer>> subsets(int[] S) {
        // Start typing your Java solution below
        // DO NOT write main() function
        ArrayList<ArrayList<Integer>> results = new ArrayList<ArrayList<Integer>>();
        boolean[] visit = new boolean[S.length];
        work(S, visit, 0, results);
        return results;
    }
    
    public void work(int[] S, boolean[] visit, int index, ArrayList<ArrayList<Integer>> results) {
        if (index >= S.length) {
            ArrayList<Integer> item = new ArrayList<Integer>();
            for (int i=0; i<S.length; i++)
                if (visit[i])
                    item.add(S[i]);
            Collections.sort(item);
            results.add(item);
            return;
        }
        visit[index] = false;
        work(S, visit, index+1, results);
        visit[index] = true;
        work(S, visit, index+1, results);
    }
}

실행 결과:
Run Status: 
Accepted!
Program Runtime: 
604 milli secs
Progress: 
10/
10 test cases passed.

좋은 웹페이지 즐겨찾기