Generating power set recursively without any loops

前端 未结 8 1249
执笔经年
执笔经年 2020-12-16 18:50

How do you write a recursive method PowerSet(String input) that prints out all possible combinations of a string that is passed to it?

For example: PowerSet(\"abc\")

8条回答
  •  自闭症患者
    2020-12-16 19:11

    Simple solution but with poor time complexity(2^n) is as following(just keep one thing in mind once we have to avoid(i.e. 0) and once we have to take it(i.e. 1):

    public HashSet powerSet(int n) {
        return calcPowerSet(n-1, new HashSet(), new int[n]);
    }
    
    private HashSet calcPowerSet(int n, HashSet result, int []set) {
        if(n < 0) {
            result.add(set.clone());
            return null;
        }
        else {
            set[n] = 0;
            calcPowerSet(n-1, result, set);
            set[n] = 1;
            calcPowerSet(n-1, result, set);
            return result;
        }
    }
    

提交回复
热议问题